Example usage for org.apache.poi.ss.usermodel Sheet setColumnWidth

List of usage examples for org.apache.poi.ss.usermodel Sheet setColumnWidth

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Sheet setColumnWidth.

Prototype

void setColumnWidth(int columnIndex, int width);

Source Link

Document

Set the width (in units of 1/256th of a character width)

The maximum column width for an individual cell is 255 characters.

Usage

From source file:com.report.template.LoanCalculator.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;//  ww w.  ja va2s  . c  o m

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 11 * 256);
    sheet.setColumnWidth(3, 14 * 256);
    sheet.setColumnWidth(4, 14 * 256);
    sheet.setColumnWidth(5, 14 * 256);
    sheet.setColumnWidth(6, 14 * 256);

    createNames(wb);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 1; i <= 7; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple Loan Calculator");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(4);
    cell.setCellValue("Enter values");
    cell.setCellStyle(styles.get("item_right"));

    row = sheet.createRow(3);
    cell = row.createCell(2);
    cell.setCellValue("Loan amount");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellValue("123123");
    cell.setCellStyle(styles.get("input_$"));
    cell.setAsActiveCell();

    row = sheet.createRow(4);
    cell = row.createCell(2);
    cell.setCellValue("Annual interest rate");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_%"));

    row = sheet.createRow(5);
    cell = row.createCell(2);
    cell.setCellValue("Loan period in years");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_i"));

    row = sheet.createRow(6);
    cell = row.createCell(2);
    cell.setCellValue("Start date of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_d"));

    row = sheet.createRow(8);
    cell = row.createCell(2);
    cell.setCellValue("Monthly payment");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(9);
    cell = row.createCell(2);
    cell.setCellValue("Number of payments");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");
    cell.setCellStyle(styles.get("formula_i"));

    row = sheet.createRow(10);
    cell = row.createCell(2);
    cell.setCellValue("Total interest");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(11);
    cell = row.createCell(2);
    cell.setCellValue("Total cost of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    // Write the output to a file
    String file = "loan-calculator.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:com.sofrecom.analyser.Analyser.java

private static void printXlsx(List<SecurityPattern> listOfRoutesToDelete,
        List<SecurityPattern> listOfRoutesToInsert) throws IOException {
    Runtime.getRuntime().exec("taskkill /f /t /IM excel.exe");

    try (final FileOutputStream fileOut = new FileOutputStream("BI_MODULE.xlsx")) {
        final WorkbookContext wbContext = new WorkbookContext();
        final Sheet insertSheet = wbContext.wb.createSheet("Insert list");
        insertSheet.setDisplayGridlines(false);

        Row r = insertSheet.createRow(0);
        insertSheet.setColumnWidth(0, 3000);
        insertSheet.setColumnWidth(1, 14250);
        insertSheet.setColumnWidth(2, 3000);
        insertSheet.setColumnWidth(3, 4050);
        insertSheet.setColumnWidth(4, 3000);
        for (int i = 0; i < SecurityPattern.getSchema().length; i++) {
            r.createCell(i).setCellValue(SecurityPattern.getSchema()[i]);
        }/*  w  w  w  . j av  a  2  s .co m*/

        for (SecurityPattern insertRoute : listOfRoutesToInsert) {
            Row row = wbContext.nextRow(insertSheet);
            row.createCell(0).setCellValue(insertRoute.PATTERN_ID);
            row.createCell(1).setCellValue(insertRoute.SEC_PATTERN);
            row.createCell(2).setCellValue(insertRoute.METHOD);
            row.createCell(3).setCellValue("0");
            row.createCell(4).setCellValue("");
            row.createCell(5).setCellValue("false");
        }

        final Sheet delteteSheet = wbContext.wb.createSheet("delete list");
        wbContext.CURRENT_ROW_INDEX = 1;
        delteteSheet.setDisplayGridlines(false);

        r = delteteSheet.createRow(0);
        delteteSheet.setColumnWidth(0, 3000);
        delteteSheet.setColumnWidth(1, 14250);
        delteteSheet.setColumnWidth(2, 3000);
        delteteSheet.setColumnWidth(3, 4050);
        delteteSheet.setColumnWidth(4, 3000);
        for (int i = 0; i < SecurityPattern.getSchema().length; i++) {
            r.createCell(i).setCellValue(SecurityPattern.getSchema()[i]);
        }

        for (SecurityPattern insertRoute : listOfRoutesToDelete) {
            Row row = wbContext.nextRow(delteteSheet);
            row.createCell(0).setCellValue(insertRoute.PATTERN_ID);
            row.createCell(1).setCellValue(insertRoute.SEC_PATTERN);
            row.createCell(2).setCellValue(insertRoute.METHOD);
            row.createCell(3).setCellValue(insertRoute.MATCHER_TYPE);
            if (insertRoute.FN_ID != null)
                row.createCell(4).setCellValue(insertRoute.FN_ID);
            else
                row.createCell(4).setCellValue("Null");
            row.createCell(5).setCellValue(String.valueOf(insertRoute.ALLOWED));
        }

        wbContext.wb.write(fileOut);
        fileOut.close();
    }
    Desktop.getDesktop().open(new File("BI_MODULE.xlsx"));
}

From source file:com.solidmaps.webapp.report.TimesheetDemo.java

License:Apache License

public void main(String[] args) throws Exception {
    Workbook wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);//from  ww w.j a  v  a 2 s .co m
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    //title row
    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue("Weekly Timesheet");
    titleCell.setCellStyle(styles.get("title"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));

    //header row
    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    for (int i = 0; i < titles.length; i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(titles[i]);
        headerCell.setCellStyle(styles.get("header"));
    }

    int rownum = 2;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles.length; j++) {
            Cell cell = row.createCell(j);
            if (j == 9) {
                //the 10th cell contains sum over week days, e.g. SUM(C3:I3)
                String ref = "C" + rownum + ":I" + rownum;
                cell.setCellFormula("SUM(" + ref + ")");
                cell.setCellStyle(styles.get("formula"));
            } else if (j == 11) {
                cell.setCellFormula("J" + rownum + "-K" + rownum);
                cell.setCellStyle(styles.get("formula"));
            } else {
                cell.setCellStyle(styles.get("cell"));
            }
        }
    }

    //row with totals below
    Row sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(35);
    Cell cell;
    cell = sumRow.createCell(0);
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellValue("Total Hrs:");
    cell.setCellStyle(styles.get("formula"));

    for (int j = 2; j < 12; j++) {
        cell = sumRow.createCell(j);
        String ref = (char) ('A' + j) + "3:" + (char) ('A' + j) + "12";
        cell.setCellFormula("SUM(" + ref + ")");
        if (j >= 9)
            cell.setCellStyle(styles.get("formula_2"));
        else
            cell.setCellStyle(styles.get("formula"));
    }
    rownum++;
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Regular Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("L13");
    cell.setCellStyle(styles.get("formula_2"));
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Overtime Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("K13");
    cell.setCellStyle(styles.get("formula_2"));

    //set sample data
    for (int i = 0; i < sample_data.length; i++) {
        Row row = sheet.getRow(2 + i);
        for (int j = 0; j < sample_data[i].length; j++) {
            if (sample_data[i][j] == null)
                continue;

            if (sample_data[i][j] instanceof String) {
                row.getCell(j).setCellValue((String) sample_data[i][j]);
            } else {
                row.getCell(j).setCellValue((Double) sample_data[i][j]);
            }
        }
    }

    //finally set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 30 * 256); //30 characters wide
    for (int i = 2; i < 9; i++) {
        sheet.setColumnWidth(i, 6 * 256); //6 characters wide
    }
    sheet.setColumnWidth(10, 10 * 256); //10 characters wide

    // Write the output to a file
    String file = "/home/brunorocca/Desktop/mapa_teste.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:com.springapp.mvc.BusinessPlan.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/* w w  w  . j  ava2 s  . c  o  m*/

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Business Plan");

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    //the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    //columns for 11 weeks starting from 9-Jul
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);

    //calendar.setTime(fmt.parse("9-11"));
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    //freeze the first row
    sheet.createFreezePane(0, 1);

    Row row;
    Cell cell;
    int rownum = 1;
    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            cell = row.createCell(j);
            String styleName;
            boolean isHeader = i == 0 || data[i - 1] == null;
            switch (j) {
            case 0:
                if (isHeader) {
                    styleName = "cell_b";
                    cell.setCellValue(Double.parseDouble(data[i][j]));
                } else {
                    styleName = "cell_normal";
                    cell.setCellValue(data[i][j]);
                }
                break;
            case 1:
                if (isHeader) {
                    styleName = i == 0 ? "cell_h" : "cell_bb";
                } else {
                    styleName = "cell_indented";
                }
                cell.setCellValue(data[i][j]);
                break;
            case 2:
                styleName = isHeader ? "cell_b" : "cell_normal";
                cell.setCellValue(data[i][j]);
                break;
            case 3:
                styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                cell.setCellValue(Integer.parseInt(data[i][j]));
                break;
            case 4: {
                //calendar.setTime(fmt.parse(data[i][j]));
                calendar.set(Calendar.YEAR, year);
                cell.setCellValue(calendar);
                styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                break;
            }
            case 5: {
                int r = rownum + 1;
                String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")";
                cell.setCellFormula(fmla);
                styleName = isHeader ? "cell_bg" : "cell_g";
                break;
            }
            default:
                styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
            }

            cell.setCellStyle(styles.get(styleName));
        }
    }

    //group rows for each phase, row numbers are 0-based
    sheet.groupRow(4, 6);
    sheet.groupRow(9, 13);
    sheet.groupRow(16, 18);

    //set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 256 * 6);
    sheet.setColumnWidth(1, 256 * 33);
    sheet.setColumnWidth(2, 256 * 20);
    sheet.setZoom(3, 4);

    // Write the output to a file
    String file = "businessplan.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:com.tecnosur.util.Excel.java

public void ExportarMatriculados(CControlmatricula datos, String aula) {
    try { // Defino el Libro de Excel
        HSSFWorkbook wb = new HSSFWorkbook();

        // Creo la Hoja en Excel
        Sheet sheet = wb.createSheet("matriculados");

        // quito las lineas del libro para darle un mejor acabado
        sheet.setDisplayGridlines(false);
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));

        // creo una nueva fila
        Row trow = sheet.createRow((short) 1);

        createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                "ALUMNOS MATRICULADOS");

        Row trow2 = sheet.createRow((short) 3);
        createTituloCell(wb, trow2, 0, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER, "AULA: " + aula);

        // Creo la cabecera de mi listado en Excel
        Row row = sheet.createRow((short) 5);

        // Creo las celdas de mi fila, se puede poner un diseo a la celda_codigo
        createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "CDIGO", true, true);
        createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "ALUMNO", true, true);
        createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "TIPO PAGO", true, true);
        createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "CRONO. PAGO", true, true);
        createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "N CUOT.", true, true);
        createCell(wb, row, 5, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "MON. MATR.", true, true);
        createCell(wb, row, 6, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "MON. CUOT.", true, true);

        // Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que 
        //la celda_codigo se acomode segn su tamao
        Sheet ssheet = wb.getSheetAt(0);
        ssheet.setColumnWidth(0, 60 * 40);
        ssheet.setColumnWidth(1, 255 * 40);
        ssheet.setColumnWidth(2, 90 * 40);
        ssheet.autoSizeColumn(3);/*from   w  w  w . j a  va2  s . c  o  m*/
        ssheet.autoSizeColumn(4);
        ssheet.autoSizeColumn(5);
        ssheet.autoSizeColumn(6);

        HSSFFont cellFont = wb.createFont();

        cellFont.setFontHeightInPoints((short) 8);
        cellFont.setFontName(HSSFFont.FONT_ARIAL);

        CellStyle cellStyle = wb.createCellStyle();

        cellStyle.setFont(cellFont);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setLeftBorderColor((short) 8);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setRightBorderColor((short) 8);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBottomBorderColor((short) 8);

        for (int i = 0; i < datos.size(); i++) {
            row = sheet.createRow((short) i + 6);
            Cell celda_codigo = row.createCell(0);

            celda_codigo.setCellStyle(cellStyle);
            celda_codigo.setCellValue(datos.get(i).getIdalumno());

            Cell celda_alumno = row.createCell(1);
            celda_alumno.setCellStyle(cellStyle);
            celda_alumno.setCellValue(datos.get(i).getNom_completo());

            Cell celda_tipopago = row.createCell(2);
            celda_tipopago.setCellStyle(cellStyle);
            celda_tipopago.setCellValue(datos.get(i).getTipopagante());

            Cell celda_crono = row.createCell(3);
            celda_crono.setCellStyle(cellStyle);
            celda_crono.setCellValue(datos.get(i).getDesc_cronopagtable());

            Cell celda_ncuota = row.createCell(4);
            celda_ncuota.setCellStyle(cellStyle);
            celda_ncuota.setCellValue(datos.get(i).getNum_cuota());

            Cell celda_matricula = row.createCell(5);
            celda_matricula.setCellStyle(cellStyle);
            celda_matricula.setCellValue(datos.get(i).getMonmatricula());

            Cell celda_moncuota = row.createCell(6);
            celda_moncuota.setCellStyle(cellStyle);
            celda_moncuota.setCellValue(datos.get(i).getMoncuota());
        }

        String strRuta = "TYSAC_Matriculados.xls";
        FileOutputStream fileOut = new FileOutputStream(strRuta);
        wb.write(fileOut);

        fileOut.close();
        Runtime.getRuntime().exec("cmd /c start " + strRuta);

    } catch (IOException e) {
        System.out.println("Error de escritura");
        e.printStackTrace();
    }
}

From source file:com.upbest.utils.AddDimensionedImage.java

License:Apache License

/**
 * Determines whether the sheets columns should be re-sized to accomodate
 * the image, adjusts the columns width if necessary and creates then
 * returns a ClientAnchorDetail object that facilitates construction of
 * an ClientAnchor that will fix the image on the sheet and establish
 * it's size./*from   w w  w. ja va 2 s .  c  o  m*/
 *
 * @param sheet A reference to the sheet that will 'contain' the image.
 * @param colNumber A primtive int that contains the index number of a
 *                  column on the sheet.
 * @param reqImageWidthMM A primitive double that contains the required
 *                        width of the image in millimetres
 * @param resizeBehaviour A primitive int whose value will indicate how the
 *                        width of the column should be adjusted if the
 *                        required width of the image is greater than the
 *                        width of the column.
 * @return An instance of the ClientAnchorDetail class that will contain
 *         the index number of the column containing the cell whose top
 *         left hand corner also defines the top left hand corner of the
 *         image, the index number column containing the cell whose top
 *         left hand corner also defines the bottom right hand corner of
 *         the image and an inset that determines how far the right hand
 *         edge of the image can protrude into the next column - expressed
 *         as a specific number of coordinate positions.
 */
private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber, double reqImageWidthMM,
        int resizeBehaviour) {

    double colWidthMM = 0.0D;
    double colCoordinatesPerMM = 0.0D;
    int pictureWidthCoordinates = 0;
    ClientAnchorDetail colClientAnchorDetail = null;

    // Get the colum's width in millimetres
    colWidthMM = ConvertImageUnits.widthUnits2Millimetres((short) sheet.getColumnWidth(colNumber));

    // Check that the column's width will accomodate the image at the
    // required dimension. If the width of the column is LESS than the
    // required width of the image, decide how the application should
    // respond - resize the column or overlay the image across one or more
    // columns.
    if (colWidthMM < reqImageWidthMM) {

        // Should the column's width simply be expanded?
        if ((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)
                || (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) {
            // Set the width of the column by converting the required image
            // width from millimetres into Excel's column width units.
            sheet.setColumnWidth(colNumber, ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM));
            // To make the image occupy the full width of the column, convert
            // the required width of the image into co-ordinates. This value
            // will become the inset for the ClientAnchorDetail class that
            // is then instantiated.
            if (sheet instanceof HSSFSheet) {
                colWidthMM = reqImageWidthMM;
                colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / colWidthMM;
                pictureWidthCoordinates = (int) (reqImageWidthMM * colCoordinatesPerMM);

            } else {
                pictureWidthCoordinates = (int) reqImageWidthMM * AddDimensionedImage.EMU_PER_MM;
            }
            colClientAnchorDetail = new ClientAnchorDetail(colNumber, colNumber, pictureWidthCoordinates);
        }
        // If the user has chosen to overlay both rows and columns or just
        // to expand ONLY the size of the rows, then calculate how to lay
        // the image out across one or more columns.
        else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)
                || (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) {
            colClientAnchorDetail = this.calculateColumnLocation(sheet, colNumber, reqImageWidthMM);
        }
    }
    // If the column is wider than the image.
    else {
        if (sheet instanceof HSSFSheet) {
            // Mow many co-ordinate positions are there per millimetre?
            colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / colWidthMM;
            // Given the width of the image, what should be it's co-ordinate?
            pictureWidthCoordinates = (int) (reqImageWidthMM * colCoordinatesPerMM);
        } else {
            pictureWidthCoordinates = (int) reqImageWidthMM * AddDimensionedImage.EMU_PER_MM;
        }
        colClientAnchorDetail = new ClientAnchorDetail(colNumber, colNumber, pictureWidthCoordinates);
    }
    return (colClientAnchorDetail);
}

From source file:com.vincestyling.apkinfoextractor.core.export.ExportToExcel.java

License:Apache License

@Override
public void export() throws Exception {
    Workbook wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet(Constancts.APP_NAME);
    sheet.setHorizontallyCenter(true);/*from  w  ww  . ja v a  2 s . c o  m*/
    sheet.setFitToPage(true);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(
            "  File generated by ApkInfoExtractor (https://github.com/vince-styling/ApkInfoExtractor), Copyright (C) 2014 Vince Styling");
    titleCell.setCellStyle(styles.get("title"));

    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);

    int cellNum = 0;
    String[] fields = solution.getExtractFields().split(",");
    for (String field : fields) {
        if (field.equals(Constancts.ICON))
            continue;
        Cell headerCell = headerRow.createCell(cellNum);
        headerCell.setCellValue(field);
        headerCell.setCellStyle(styles.get("header"));
        sheet.setColumnWidth(cellNum, ApkInfo.getFieldCharacterCount(field) * 256);
        cellNum++;
    }

    int rowNum = 2;
    for (int i = 0; i < solution.getResultCount(); i++) {
        ResultDataProvider provider = solution.getResultList().get(i);
        postProgress(i + 1);

        cellNum = 0;
        Row row = sheet.createRow(rowNum++);
        for (String field : fields) {
            if (field.equals(Constancts.ICON))
                continue;
            Cell cell = row.createCell(cellNum);
            cell.setCellStyle(styles.get("cell"));
            String value = getFieldValue(provider.getApkInfo(), field);
            cell.setCellValue(value);
            cellNum++;
        }
        row.setHeight((short) (5 * 256));
    }

    File outputFile = new File(solution.getWorkingFolder(), solution.generateOutputFileName() + ".xls");
    FileOutputStream out = new FileOutputStream(outputFile);
    wb.write(out);
    out.close();

    callback.onProcessSuccess(outputFile);
}

From source file:com.wantdo.stat.excel.poi_src.AligningCells.java

License:Apache License

public static void main(String[] args) throws IOException {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();

    Sheet sheet = wb.createSheet();
    Row row = sheet.createRow((short) 2);
    row.setHeightInPoints(30);//  w  w w .ja  v  a2 s .c o  m
    for (int i = 0; i < 8; i++) {
        //column width is set in units of 1/256th of a character width
        sheet.setColumnWidth(i, 256 * 15);
    }

    createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
    createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
    createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

From source file:com.zhangyue.zeus.service.impl.ExportDataServiceImpl.java

License:Open Source License

@Override
public void downloadData(OutputStream os, String hdfsResultLocation, boolean isDownload) {
    List<String> resultList = readResultData(hdfsResultLocation, isDownload);
    if (resultList.size() == 0) {
        return;/*ww  w.  jav  a 2  s. c o m*/
    }
    Workbook book = new HSSFWorkbook();
    Sheet sheet = book.createSheet(Constants.SHEET_NAME);
    sheet.setColumnWidth(0, 10000);
    for (int i = 0; i < resultList.size(); i++) {
        Row row = sheet.createRow(i);
        if (null == resultList.get(i)) {
            continue;
        }
        String[] items = resultList.get(i).split(Constants.HIVE_RESULT_TAG);
        for (int j = 0; j < items.length; j++) {
            row.createCell(j).setCellValue(items[j]);
        }
    }
    try {
        book.write(os);
        os.flush();
        os.close();
    } catch (IOException e) {
        LOG.error("Export excel error!!", e);
    }
}

From source file:Compras.altaCompras.java

   private void b_muestraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_muestraActionPerformed
    // TODO add your handling code here:
    javax.swing.JFileChooser jF1= new javax.swing.JFileChooser();
    jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
    String ruta = null;/*  ww  w . jav a2  s .co  m*/
    if(jF1.showSaveDialog(null)==jF1.APPROVE_OPTION)
    {
        ruta = jF1.getSelectedFile().getAbsolutePath();
        File archivoXLS = new File(ruta+".xls");
        try
        {
            if(archivoXLS.exists())
            archivoXLS.delete();
            archivoXLS.createNewFile();
            Workbook libro = new HSSFWorkbook();
            FileOutputStream archivo = new FileOutputStream(archivoXLS);
            Sheet hoja = libro.createSheet("Muestras");
                
            org.apache.poi.ss.usermodel.Font font10 = libro.createFont();
            font10.setFontHeightInPoints((short)10);
            font10.setFontName("Arial");
            font10.setItalic(false);
            font10.setBold(false);
            font10.setColor(new HSSFColor.YELLOW().getIndex());
                
                
            CellStyle titulo = libro.createCellStyle();
            CellStyle contenido = libro.createCellStyle();
            CellStyle firma = libro.createCellStyle();
            CellStyle costado = libro.createCellStyle();
            CellStyle derecha = libro.createCellStyle();
            CellStyle derecha_borde = libro.createCellStyle();
                
            titulo.setFont(font10);
            titulo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            titulo.setFillBackgroundColor(new HSSFColor.GREEN().getIndex());
            titulo.setAlignment(CellStyle.ALIGN_CENTER);
                
            contenido.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            contenido.setBorderTop(HSSFCellStyle.BORDER_THIN);
            contenido.setBorderRight(HSSFCellStyle.BORDER_THIN);
            contenido.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                
            derecha_borde.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setBorderTop(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setBorderRight(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            derecha_borde.setAlignment(CellStyle.ALIGN_RIGHT);
                
            derecha.setAlignment(CellStyle.ALIGN_RIGHT);
                
            firma.setBorderTop(HSSFCellStyle.BORDER_THIN);
            firma.setAlignment(CellStyle.ALIGN_CENTER);
                
            //costado.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                
            hoja.setColumnWidth(0, 3000);
            hoja.setColumnWidth(2, 3000);
            hoja.setColumnWidth(3, 8000);
            hoja.setColumnWidth(4, 5000);
            try
            {
                InputStream is = new FileInputStream("imagenes/grande300115.jpg");
                byte[] bytes = IOUtils.toByteArray(is);
                int pictureIdx = libro.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
                is.close();
                CreationHelper helper = libro.getCreationHelper();
                Drawing drawing = hoja.createDrawingPatriarch();
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(0);
                anchor.setRow1(0);
                Picture pict = drawing.createPicture(anchor, pictureIdx);
                pict.resize();
            }catch(Exception e){e.printStackTrace();}
            Row r7 = hoja.createRow(7);
            r7.createCell(0).setCellValue("ORDEN:");
            r7.createCell(1).setCellValue(String.valueOf(ord.getIdOrden()));
            r7.createCell(2).setCellValue("Hrs. Entrega:");
            r7.createCell(3).setCellValue("");
            hoja.addMergedRegion(new CellRangeAddress(7,7,4,7));
            r7.createCell(4).setCellValue("ORDEN PARA SURTIR MUESTRAS");
            r7.getCell(4).setCellStyle(derecha);
                
            Date fecha = new Date();
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");//YYYY-MM-DD HH:MM:SS
            String valor=dateFormat.format(fecha);
            Row r8 = hoja.createRow(8);
            r8.createCell(0).setCellValue("Supervisor:");
            hoja.addMergedRegion(new CellRangeAddress(8,8,1,3));
            r8.createCell(1).setCellValue("");
            r8.createCell(4).setCellValue("F. Elaboracin:");
            r8.createCell(5).setCellValue(valor);
                
            Row r9 = hoja.createRow(9);
            r9.createCell(0).setCellValue("Comprador:");
            hoja.addMergedRegion(new CellRangeAddress(9,9,1,3));
            r9.createCell(1).setCellValue("");
            r9.createCell(4).setCellValue("F. Entrega:");
            r9.createCell(5).setCellValue("");
                
            Row r10 = hoja.createRow(10);
            r10.createCell(0).setCellValue("Cantidad");
            r10.getCell(0).setCellStyle(titulo);
            hoja.addMergedRegion(new CellRangeAddress(10,10,1,7));
            r10.createCell(1).setCellValue("Descripcin");
            r10.getCell(1).setCellStyle(titulo);
                
            int ren=11;
            for(int r=0;r<(t_datos.getRowCount());r++)
            {
                if((boolean)t_titulos.getValueAt(r, 3)==true)
                {
                    Row fila = hoja.createRow(ren);
                    Cell celda = fila.createCell(0);
                    celda.setCellStyle(derecha_borde);
                    Cell celda1 = fila.createCell(1);
                    celda1.setCellStyle(contenido);
                    fila.createCell(2).setCellStyle(contenido);
                    fila.createCell(3).setCellStyle(contenido);
                    fila.createCell(4).setCellStyle(contenido);
                    fila.createCell(5).setCellStyle(contenido);
                    fila.createCell(6).setCellStyle(contenido);
                    fila.createCell(7).setCellStyle(contenido);
                    //Cell celda8 = fila.createCell(8);
                    //celda8.setCellStyle(costado);
                    try{
                        celda.setCellValue(t_datos.getValueAt(r, 14).toString());
                        hoja.addMergedRegion(new CellRangeAddress(ren,ren,1,7));
                        celda1.setCellValue(t_titulos.getValueAt(r, 2).toString());
                        //celda8.setCellValue("");
                    }catch(Exception e){
                        celda.setCellValue("");
                    }
                    ren++;
                }
            }
                
            Row rx = hoja.createRow(ren+5);
            hoja.addMergedRegion(new CellRangeAddress(ren+5,ren+5,0,2));
            rx.createCell(0).setCellValue("Recibe Muestras");
            rx.getCell(0).setCellStyle(firma);
            rx.createCell(1).setCellStyle(firma);
            rx.createCell(2).setCellStyle(firma);
            hoja.addMergedRegion(new CellRangeAddress(ren+5,ren+5,5,7));
            rx.createCell(5).setCellValue("Entrega Muestras");
            rx.getCell(5).setCellStyle(firma);
            rx.createCell(6).setCellStyle(firma);
            rx.createCell(7).setCellStyle(firma);
                
            libro.write(archivo);
            archivo.close();
            Desktop.getDesktop().open(archivoXLS);
        }catch(Exception e)
        {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "No se pudo realizar el reporte si el archivo esta abierto");
        }
    }
}