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

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

Introduction

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

Prototype

void autoSizeColumn(int column, boolean useMergedCells);

Source Link

Document

Adjusts the column width to fit the contents.

Usage

From source file:br.com.tecsinapse.dataio.util.WorkbookUtil.java

License:LGPL

public Workbook toWorkBook(Workbook wb, Table table) {
    List<List<TableCell>> matrix = table.getCells();
    List<List<TableCell>> matrixFull = table.toTableCellMatrix();

    replaceColorsPallete(table.getColorsReplaceMap(), wb);

    String sheetName = table.getTitle();
    Sheet sheet = sheetName == null ? wb.createSheet() : wb.createSheet(sheetName);
    int titleRows = 0;
    int r = titleRows;
    int c = 0;//from   w  ww  .j  av  a  2 s.co  m
    int maxColumns = -1;
    Map<Integer, Integer> defaultColumnWidth = new HashMap<>();

    ExporterFormatter tableExporterFormatter = table.getExporterFormatter();

    for (List<TableCell> row : matrix) {
        Row sheetRow = sheet.createRow(r);

        for (TableCell tableCell : row) {
            while (matrixFull.get(r - titleRows).get(c) == EmptyTableCell.EMPTY_CELL) {
                c++;
                if (c >= matrixFull.get(r - titleRows).size()) {
                    c = 0;
                    r++;
                }
            }

            Cell cell = sheetRow.createCell(c);
            if (c > maxColumns) {
                maxColumns = c;
            }

            if (tableCell.getRowspan() > 1 || tableCell.getColspan() > 1) {
                int rowStart = r;
                int rowEnd = rowStart + (tableCell.getRowspan() - 1);
                int colStart = c;
                int colEnd = colStart + (tableCell.getColspan() - 1);

                CellRangeAddress cellRange = new CellRangeAddress(rowStart, rowEnd, colStart, colEnd);
                sheet.addMergedRegion(cellRange);

                RegionUtil.setBorderTop(BorderStyle.THIN, cellRange, sheet);
                RegionUtil.setBorderRight(BorderStyle.THIN, cellRange, sheet);
                RegionUtil.setBorderBottom(BorderStyle.THIN, cellRange, sheet);
                RegionUtil.setBorderLeft(BorderStyle.THIN, cellRange, sheet);
            } else if (!table.isAutoSizeColumnSheet()) {
                Integer maxColumnWidth = defaultColumnWidth.get(c);
                if (maxColumnWidth == null) {
                    defaultColumnWidth.put(c, tableCell.getDefaultColumnWidth());
                } else {
                    int defaultWidth = tableCell.getDefaultColumnWidth();
                    if (defaultWidth > maxColumnWidth) {
                        defaultColumnWidth.put(c, defaultWidth);
                    }
                }
            }

            String format = setConvertedValue(cell, tableCell, tableExporterFormatter);
            setCellStyle(cell, tableCell, wb, format);
            c++;
        }
        r++;
        c = 0;
    }

    if (table.isAutoSizeColumnSheet()) {
        for (int i = 0; i <= maxColumns; ++i) {
            if (sheet instanceof SXSSFSheet) {
                ((SXSSFSheet) sheet).trackColumnForAutoSizing(i);
            }
            sheet.autoSizeColumn(i, true);
        }
    } else {
        for (int i = 0; i <= maxColumns; ++i) {
            if (defaultColumnWidth.get(i) == null) {
                if (sheet instanceof SXSSFSheet) {
                    ((SXSSFSheet) sheet).trackColumnForAutoSizing(i);
                }
                sheet.autoSizeColumn(i, true);
            } else {
                int width = table.getMinOrMaxOrActualCellWidth(defaultColumnWidth.get(i));
                sheet.setColumnWidth(i, width);
            }
        }
    }
    return wb;
}

From source file:br.com.tecsinapse.exporter.util.WorkbookUtil.java

License:LGPL

public Workbook toWorkBook(Workbook wb, Table table) {
    List<List<TableCell>> matrix = table.getCells();
    List<List<TableCell>> matrixFull = table.toTableCellMatrix();

    String sheetName = table.getTitle();
    Sheet sheet = sheetName == null ? wb.createSheet() : wb.createSheet(sheetName);
    int titleRows = 0;
    int r = titleRows;
    int c = 0;// w ww  . j av  a  2 s  .c o m
    int maxColumns = -1;
    Map<Integer, Integer> defaultColumnWidth = new HashMap<>();

    ExporterFormatter tableExporterFormatter = table.getExporterFormatter();

    for (List<TableCell> row : matrix) {
        Row sheetRow = sheet.createRow(r);

        for (TableCell tableCell : row) {
            while (matrixFull.get(r - titleRows).get(c) == EmptyTableCell.EMPTY_CELL) {
                c++;
                if (c >= matrixFull.get(r - titleRows).size()) {
                    c = 0;
                    r++;
                }
            }

            Cell cell = sheetRow.createCell(c);
            if (c > maxColumns) {
                maxColumns = c;
            }

            if (tableCell.getRowspan() > 1 || tableCell.getColspan() > 1) {
                int rowStart = r;
                int rowEnd = rowStart + (tableCell.getRowspan() - 1);
                int colStart = c;
                int colEnd = colStart + (tableCell.getColspan() - 1);

                CellRangeAddress cellRange = new CellRangeAddress(rowStart, rowEnd, colStart, colEnd);
                sheet.addMergedRegion(cellRange);

                RegionUtil.setBorderTop(1, cellRange, sheet, wb);
                RegionUtil.setBorderRight(1, cellRange, sheet, wb);
                RegionUtil.setBorderBottom(1, cellRange, sheet, wb);
                RegionUtil.setBorderLeft(1, cellRange, sheet, wb);
            } else if (!table.isAutoSizeColumnSheet()) {
                Integer maxColumnWidth = defaultColumnWidth.get(c);
                if (maxColumnWidth == null) {
                    defaultColumnWidth.put(c, tableCell.getDefaultColumnWidth());
                } else {
                    int defaultWidth = tableCell.getDefaultColumnWidth();
                    if (defaultWidth > maxColumnWidth) {
                        defaultColumnWidth.put(c, defaultWidth);
                    }
                }
            }

            String format = setConvertedValue(cell, tableCell, tableExporterFormatter);
            setCellStyle(cell, tableCell, wb, format);
            c++;
        }
        r++;
        c = 0;
    }

    if (table.isAutoSizeColumnSheet()) {
        for (int i = 0; i <= maxColumns; ++i) {
            if (sheet instanceof SXSSFSheet) {
                ((SXSSFSheet) sheet).trackColumnForAutoSizing(i);
            } else {
                sheet.autoSizeColumn(i, true);
            }
        }
    } else {
        for (int i = 0; i <= maxColumns; ++i) {
            if (defaultColumnWidth.get(i) == null) {
                if (sheet instanceof SXSSFSheet) {
                    ((SXSSFSheet) sheet).trackColumnForAutoSizing(i);
                } else {
                    sheet.autoSizeColumn(i, true);
                }
            } else {
                sheet.setColumnWidth(i, defaultColumnWidth.get(i));
            }
        }
    }
    return wb;
}

From source file:com.catexpress.util.FormatosPOI.java

public void formatoSolicitud(Solicitud solicitud, Set<Proveedor> proveedores)
        throws FileNotFoundException, IOException {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet;
    int cont = 0;
    for (Proveedor proveedor : proveedores) {
        sheet = wb.createSheet(proveedor.getNombre());
        Row rTitulo = sheet.createRow(0);
        CellRangeAddress craTitulo = new CellRangeAddress(0, //first row (0-based)
                0, //last row  (0-based)
                0, //first column (0-based)
                6 //last column  (0-based)
        );/*w  ww .  j  a  v a2s.com*/
        sheet.addMergedRegion(craTitulo);
        Cell titulo = rTitulo.createCell(0);
        titulo.setCellValue("SOLICITUD DE MERCANC?A");
        titulo.setCellStyle(estiloHeader(wb, TITULO));
        rTitulo.setHeightInPoints(20);

        Row rUsuario = sheet.createRow(1);
        CellRangeAddress craUsuario = new CellRangeAddress(1, 1, 0, 6);
        sheet.addMergedRegion(craUsuario);
        Cell usuario = rUsuario.createCell(0);
        usuario.setCellValue((solicitud.getUsuario().getNombre() + " " + solicitud.getUsuario().getApPaterno()
                + " " + solicitud.getUsuario().getApMaterno()).toUpperCase());
        usuario.setCellStyle(estiloHeader(wb, USUARIO));
        rUsuario.setHeightInPoints(25);

        Row rSucursal = sheet.createRow(2);
        CellRangeAddress craSucursal = new CellRangeAddress(2, 2, 0, 6);
        sheet.addMergedRegion(craSucursal);
        Cell sucursal = rSucursal.createCell(0);
        sucursal.setCellValue("Sucursal: " + solicitud.getSucursal().getNombre());
        sucursal.setCellStyle(estiloHeader(wb, SUCURSAL));
        RegionUtil.setBorderTop(sucursal.getCellStyle().getBorderTop(), craSucursal, sheet, wb);
        RegionUtil.setBorderLeft(sucursal.getCellStyle().getBorderLeft(), craSucursal, sheet, wb);
        RegionUtil.setBorderRight(sucursal.getCellStyle().getBorderRight(), craSucursal, sheet, wb);
        RegionUtil.setBorderBottom(sucursal.getCellStyle().getBorderBottom(), craSucursal, sheet, wb);
        rSucursal.setHeightInPoints(20);

        Row rBlank = sheet.createRow(3);
        Cell blank;
        for (int i = 0; i <= 6; i++) {
            blank = rBlank.createCell(i);
            blank.setCellStyle(estiloVacio(wb));
        }

        Row rFecha = sheet.createRow(4);
        Cell labelFecha = rFecha.createCell(0);
        labelFecha.setCellValue("FECHA:");
        labelFecha.setCellStyle(estiloHeader(wb, LABEL));
        CellRangeAddress craFecha = new CellRangeAddress(4, 4, 1, 3);
        sheet.addMergedRegion(craFecha);
        Cell fecha = rFecha.createCell(1);
        fecha.setCellValue(solicitud.getFechaSolicitud());
        fecha.setCellStyle(estiloHeader(wb, FECHA));
        for (int i = 4; i <= 6; i++) {
            blank = rFecha.createCell(i);
            blank.setCellStyle(estiloVacio(wb));
        }

        Row rVigencia = sheet.createRow(5);
        Cell labelVigencia = rVigencia.createCell(0);
        labelVigencia.setCellValue("VIGENCIA:");
        labelVigencia.setCellStyle(estiloHeader(wb, LABEL));
        CellRangeAddress craVigencia = new CellRangeAddress(5, 5, 1, 3);
        sheet.addMergedRegion(craVigencia);
        Cell vigencia = rVigencia.createCell(1);
        Calendar clndr = Calendar.getInstance();
        clndr.setTime(solicitud.getFechaSolicitud());
        clndr.add(Calendar.DAY_OF_MONTH, 3);
        vigencia.setCellValue(clndr.getTime());
        vigencia.setCellStyle(estiloHeader(wb, FECHA));
        blank = rVigencia.createCell(4);
        blank.setCellStyle(estiloVacio(wb));
        Cell labelNoPedido = rVigencia.createCell(5);
        labelNoPedido.setCellValue("PEDIDO No:");
        labelNoPedido.setCellStyle(estiloCuadro(wb, AMARILLO));
        Cell noPedido = rVigencia.createCell(6);
        noPedido.setCellValue(solicitud.getId());
        noPedido.setCellStyle(estiloCuadro(wb, AMARILLO));

        Row rHoja = sheet.createRow(6);
        for (int i = 0; i <= 4; i++) {
            blank = rHoja.createCell(i);
            blank.setCellStyle(estiloVacio(wb));
        }
        Cell labelHoja = rHoja.createCell(5);
        labelHoja.setCellValue("HOJA:");
        labelHoja.setCellStyle(estiloCuadro(wb, LABEL));
        Cell hoja = rHoja.createCell(6);
        hoja.setCellValue(++cont + "/" + proveedores.size());
        hoja.setCellStyle(estiloCuadro(wb, LABEL));

        Row rProveedor = sheet.createRow(7);
        CellRangeAddress craProveedor = new CellRangeAddress(7, 8, 0, 2);
        sheet.addMergedRegion(craProveedor);
        Cell prov = rProveedor.createCell(0);
        prov.setCellValue(proveedor.getNombre());
        prov.setCellStyle(estiloProveedor(wb));
        for (int i = 3; i <= 6; i++) {
            blank = rProveedor.createCell(i);
            blank.setCellStyle(estiloVacio(wb));
        }

        Row rProveedor2 = sheet.createRow(8);
        for (int i = 3; i <= 6; i++) {
            blank = rProveedor2.createCell(i);
            blank.setCellStyle(estiloVacio(wb));
        }

        Row rTotales = sheet.createRow(9);
        for (int i = 0; i <= 1; i++) {
            blank = rTotales.createCell(i);
            blank.setCellStyle(estiloVacio(wb));
        }
        Cell labelTotales = rTotales.createCell(2);
        labelTotales.setCellValue("TOTALES: ");
        labelTotales.setCellStyle(estiloTotales(wb));
        blank = rTotales.createCell(3);
        blank.setCellStyle(estiloTotales(wb));
        Cell totalSolicitado = rTotales.createCell(4);
        totalSolicitado.setCellStyle(estiloTotales(wb));
        totalSolicitado.setCellType(CellType.FORMULA);
        totalSolicitado.setCellFormula("SUM(E12:E" + (11 + solicitud.getDetalles().size()) + ")");
        Cell totalSurtido = rTotales.createCell(5);
        totalSurtido.setCellStyle(estiloTotales(wb));
        totalSurtido.setCellType(CellType.FORMULA);
        totalSurtido.setCellFormula("SUM(F12:F" + (11 + solicitud.getDetalles().size()) + ")");
        Cell totalNegado = rTotales.createCell(6);
        totalNegado.setCellStyle(estiloTotales(wb));
        totalNegado.setCellType(CellType.FORMULA);
        totalNegado.setCellFormula("SUM(G12:G" + (11 + solicitud.getDetalles().size()) + ")");

        Row rColumnas = sheet.createRow(10);
        Cell labelCodigo = rColumnas.createCell(0);
        labelCodigo.setCellValue("CODIGO");
        labelCodigo.setCellStyle(estiloColumnas(wb, COLUMNA));
        Cell labelOpciones = rColumnas.createCell(1);
        labelOpciones.setCellValue("OPCIONES");
        labelOpciones.setCellStyle(estiloColumnas(wb, COLUMNA));
        Cell labelModelo = rColumnas.createCell(2);
        labelModelo.setCellValue("MODELO / MATERIAL / COLOR");
        labelModelo.setCellStyle(estiloColumnas(wb, COLUMNA));
        Cell labelTalla = rColumnas.createCell(3);
        labelTalla.setCellValue("TALLA");
        labelTalla.setCellStyle(estiloColumnas(wb, COLUMNA));
        Cell labelSolicitado = rColumnas.createCell(4);
        labelSolicitado.setCellValue("SOLICITADO");
        labelSolicitado.setCellStyle(estiloColumnas(wb, COLUMNA));
        Cell labelSurtido = rColumnas.createCell(5);
        labelSurtido.setCellValue("SURTIDO");
        labelSurtido.setCellStyle(estiloColumnas(wb, COLUMNA));
        Cell labelNegado = rColumnas.createCell(6);
        labelNegado.setCellValue("NEGADO");
        labelNegado.setCellStyle(estiloColumnas(wb, COLUMNA));

        Row rValues = sheet.createRow(11);
        Cell codigo;
        Cell opciones;
        Cell modelo;
        Cell talla;
        Cell solicitado;
        Cell surtido;
        Cell negado;
        for (Dsolicitud detalle : solicitud.getDetalles()) {
            if (detalle.getProducto().getProvedor().equals(proveedor)) {
                codigo = rValues.createCell(0);
                codigo.setCellValue(detalle.getProducto().getCBarras());
                codigo.setCellStyle(estiloColumnas(wb, 0));
                opciones = rValues.createCell(1);
                opciones.setCellValue(" - ");
                opciones.setCellStyle(estiloColumnas(wb, 0));
                modelo = rValues.createCell(2);
                modelo.setCellValue(detalle.getProducto().getModelo().getNombre() + " / "
                        + detalle.getProducto().getColor().getNombre());
                modelo.setCellStyle(estiloColumnas(wb, 0));
                talla = rValues.createCell(3);
                talla.setCellValue(detalle.getProducto().getTalla().getNombre());
                talla.setCellStyle(estiloColumnas(wb, 0));
                solicitado = rValues.createCell(4);
                solicitado.setCellValue(detalle.getCantidad());
                solicitado.setCellStyle(estiloColumnas(wb, 0));
                surtido = rValues.createCell(5);
                surtido.setCellStyle(estiloColumnas(wb, SURTIDO));
                negado = rValues.createCell(6);
                negado.setCellStyle(estiloColumnas(wb, 0));
            }
        }

        for (int i = 0; i <= 6; i++) {
            sheet.autoSizeColumn(i, true);
        }
    }
    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("Solicitud" + solicitud.getId() + ".xls");
    wb.write(fileOut);
    fileOut.close();
}

From source file:com.emi.loan.util.Utilities.java

public static void exportTOExcel(DefaultTableModel dtm, Map<String, String> ln_info) {
    FileOutputStream out = null;//from  w w w .  j av a  2s . co  m
    try {
        Workbook wb = new HSSFWorkbook();
        //            CreationHelper createhelper = wb.getCreationHelper();
        Sheet sheet = wb.createSheet("EMI TABLE");
        Row row;
        Cell cell;
        File file = chooseFile();
        out = new FileOutputStream(file);

        HSSFFont headerFont = (HSSFFont) wb.createFont();
        headerFont.setFontHeightInPoints((short) 12);
        headerFont.setFontName("CENTURY GOTHIC");
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerFont.setColor(HSSFColor.WHITE.index);

        HSSFFont infoFont = (HSSFFont) wb.createFont();
        infoFont.setFontHeightInPoints((short) 14);
        infoFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        //            HSSFFont font = (HSSFFont) wb.createFont();
        //            font.setFontHeightInPoints((short) 10);
        //            font.setFontName("CENTURY GOTHIC");
        //            font.setColor(HSSFColor.BLACK.index);
        CellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setFillForegroundColor(HSSFColor.AQUA.index);
        defaultStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        defaultStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
        defaultStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_JUSTIFY);
        defaultStyle.setFont(headerFont);

        CellStyle borderStyle = wb.createCellStyle();
        borderStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        borderStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        borderStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        borderStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
        borderStyle.setFont(infoFont);

        row = sheet.createRow(1);
        cell = row.createCell(0);
        cell.setCellStyle(defaultStyle);
        cell.setCellValue("Loan Amount(Rs.)");

        cell = row.createCell(1);
        cell.setCellStyle(borderStyle);
        cell.setCellValue(Double.parseDouble(ln_info.get("Loan Amount")));

        row = sheet.createRow(3);
        cell = row.createCell(0);
        cell.setCellStyle(defaultStyle);
        cell.setCellValue("Interest %");

        cell = row.createCell(1);
        cell.setCellStyle(borderStyle);
        cell.setCellValue(Double.parseDouble(ln_info.get("Interest")));

        row = sheet.createRow(5);
        cell = row.createCell(0);
        cell.setCellStyle(defaultStyle);
        cell.setCellValue("Period (months)");

        cell = row.createCell(1);
        cell.setCellStyle(borderStyle);
        cell.setCellValue(Integer.parseInt(ln_info.get("Period")));

        for (int i = 0; i <= dtm.getRowCount(); i++) {

            row = sheet.createRow(i + 8);
            for (int j = 0; j < dtm.getColumnCount(); j++) {
                cell = row.createCell(j);

                if (i == 0) { // writing the column headers 

                    cell.setCellStyle(defaultStyle);
                    cell.setCellValue(dtm.getColumnName(j));

                } else if (j == 0 || j == 5) {
                    cell.setCellValue(Integer.parseInt(dtm.getValueAt(i - 1, j).toString()));
                } else {
                    cell.setCellValue(Double.parseDouble(dtm.getValueAt(i - 1, j).toString()));
                }

            }
        }

        row = sheet.createRow(dtm.getRowCount() + 12);
        cell = row.createCell(0);
        cell.setCellValue("-- END OF REPORT --");

        for (int j = 0; j < dtm.getColumnCount(); j++) {
            sheet.autoSizeColumn(j, true);
        }
        wb.write(out);
    } catch (FileNotFoundException ex) {
        System.out.println("File not Found");
        Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        System.out.println("IOException");
        Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.eyeq.pivot4j.export.poi.ExcelExporter.java

License:Common Public License

/**
 * @param context//from   w  w  w .  jav a 2 s  . co m
 * @param sheet
 */
protected void adjustColumnSizes(RenderContext context, Sheet sheet) {
    for (int i = 0; i < context.getColumnCount(); i++) {
        try {
            sheet.autoSizeColumn(getColOffset() + i, !mergedRegions.isEmpty());
        } catch (Exception e) {
            // Ignore any problem while calculating size of the columns.
        }
    }
}

From source file:com.griffinslogistics.document.excel.BDLGenerator.java

private static void generate(Workbook workbook, List<BookBoxModel> bookBoxModels, Pulsiodetails pulsiodetails,
        String packageNumber) {//from   ww  w . ja va2  s  .  c  o m

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

    Sheet sheet = workbook.createSheet(packageNumber);

    // Generate header part
    insertPulsioImage(workbook, sheet, pulsiodetails);
    insertDate(sheet, styles.get("title"));
    insertContacts(sheet, styles.get("pulsioName"), styles.get("contacts"), pulsiodetails);
    insertTitle(sheet, styles.get("title"));
    // Generate table part
    insertTableHeaders(sheet, styles.get("tableHeadersLeft"), styles.get("tableHeadersMiddle"),
            styles.get("tableHeadersRight"));
    int index = insertTableBody(sheet, styles.get("tableBodyLeft"), styles.get("tableBodyMiddle"),
            styles.get("tableBodyRight"), styles.get("tableFooters"), bookBoxModels);

    String deliveryAddress = bookBoxModels.get(0).getDeliveryAddress();
    String client = bookBoxModels.get(0).getClient();

    insertFooter(sheet, styles.get("footer"), index, packageNumber, deliveryAddress, client);

    //        Default sheet styles
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);

    sheet.autoSizeColumn(1, true);
    sheet.autoSizeColumn(2, false);
    sheet.autoSizeColumn(5, false);
    sheet.autoSizeColumn(6, false);
    sheet.autoSizeColumn(7, false);
    sheet.autoSizeColumn(8, false);

    sheet.setFitToPage(true);
}

From source file:com.griffinslogistics.document.excel.BookLabelGenerator.java

private static void generate(XSSFWorkbook workbook, BookLabelModel bookLabelModel) {
    Map<String, CellStyle> styles = createStyles(workbook);
    String title = bookLabelModel.getTitle().replace("/", "-");
    bookLabelModel.setTitle(title);//  w ww .j a  va  2  s  . co m
    //        Sheet sheet = workbook.createSheet(bookLabelModel.getBookNumber() + " " + bookLabelModel.getTitle());
    Sheet sheet = workbook.createSheet();

    for (int i = 0; i < 20; i++) {
        sheet.createRow(i);
    }

    generateHeaders(sheet, styles);
    generateAddress(sheet, styles, bookLabelModel);
    generateClient(sheet, styles, bookLabelModel);
    generateTransportation(sheet, styles, bookLabelModel);
    generateTitle(sheet, styles, bookLabelModel);
    generateCountPerBox(sheet, styles, bookLabelModel);
    generateCountPerAddress(sheet, styles, bookLabelModel);

    sheet.setColumnWidth(1, 20000);
    sheet.setColumnWidth(4, 20000);
    sheet.autoSizeColumn(0, false);
    sheet.autoSizeColumn(3, false);
    sheet.getPrintSetup().setLandscape(true);
    sheet.getPrintSetup().setPaperSize(XSSFPrintSetup.A4_PAPERSIZE);
    sheet.setFitToPage(true);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.exporter.TimeseriesExcelExportServiceImpl.java

License:Open Source License

private void adjustColumnWidths(Workbook workbook) {
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (!AbstractIntroSheetGenerator.INTRO_SHEET_NAME.equals(sheet.getSheetName())) {
            sheet.autoSizeColumn(TimeseriesExcelImporter.BB_COL_NO, false);
            sheet.setColumnWidth(TimeseriesExcelImporter.DATE_COL_NO, DATE_COL_WIDTH);
            sheet.autoSizeColumn(TimeseriesExcelImporter.VALUE_COL_NO, false);
        }//from   w w w.  j a  va2 s .com
    }
}

From source file:fi.thl.pivot.export.XlsxExporter.java

private void autosizeColumns(Sheet sheet, Pivot pivot) {
    for (int i = 0; i < pivot.getRows().size() + pivot.getColumnCount(); ++i) {
        sheet.autoSizeColumn(i, true);
    }// ww w .  java  2s  . c  o m
}

From source file:guru.qas.martini.report.DefaultState.java

License:Apache License

@Override
public void updateSuites(Sheet sheet) {
    int lastRowNum = sheet.getLastRowNum();
    Row row = sheet.createRow(0 == lastRowNum ? 0 : lastRowNum + 1);
    row.createCell(0, CellType.STRING).setCellValue("ID");
    row.createCell(1, CellType.STRING).setCellValue("Date");
    row.createCell(2, CellType.STRING).setCellValue("Name");
    row.createCell(3, CellType.STRING).setCellValue("Hostname");
    row.createCell(4, CellType.STRING).setCellValue("IP");
    row.createCell(5, CellType.STRING).setCellValue("Username");
    row.createCell(6, CellType.STRING).setCellValue("Profiles");
    row.createCell(7, CellType.STRING).setCellValue("Environment Variables");

    for (Map.Entry<String, JsonObject> mapEntry : suites.entrySet()) {
        row = sheet.createRow(sheet.getLastRowNum() + 1);

        String id = mapEntry.getKey();
        row.createCell(0, CellType.STRING).setCellValue(id);

        JsonObject suite = mapEntry.getValue();
        JsonPrimitive primitive = suite.getAsJsonPrimitive("startTimestamp");
        Long timestamp = null == primitive ? null : primitive.getAsLong();

        Cell cell = row.createCell(1);//  w  ww .j  av  a  2  s. co m
        if (null != timestamp) {
            Workbook workbook = sheet.getWorkbook();
            CellStyle cellStyle = workbook.createCellStyle();
            CreationHelper creationHelper = workbook.getCreationHelper();
            cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
            cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
            cell.setCellValue(new Date(timestamp));
            cell.setCellStyle(cellStyle);
        }

        cell = row.createCell(2);
        primitive = suite.getAsJsonPrimitive("name");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(3);
        JsonObject host = suite.getAsJsonObject("host");
        primitive = null == host ? null : host.getAsJsonPrimitive("name");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(4);
        primitive = null == host ? null : host.getAsJsonPrimitive("ip");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(5);
        primitive = null == host ? null : host.getAsJsonPrimitive("username");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(6);
        JsonArray array = suite.getAsJsonArray("profiles");
        List<String> profiles = Lists.newArrayList();
        if (null != array) {
            int size = array.size();
            for (int i = 0; i < size; i++) {
                JsonElement element = array.get(i);
                String profile = null == element ? null : element.getAsString();
                profiles.add(profile);
            }
            String profilesValue = Joiner.on('\n').skipNulls().join(profiles);
            cell.setCellValue(profilesValue);
        }

        cell = row.createCell(7);
        JsonObject environmentVariables = suite.getAsJsonObject("environment");
        Map<String, String> index = new TreeMap<>();
        if (null != environmentVariables) {
            Set<Map.Entry<String, JsonElement>> entries = environmentVariables.entrySet();
            for (Map.Entry<String, JsonElement> environmentEntry : entries) {
                String key = environmentEntry.getKey();
                JsonElement element = environmentEntry.getValue();
                String value = null == element ? "" : element.getAsString();
                index.put(key, value);
            }

            String variablesValue = Joiner.on('\n').withKeyValueSeparator('=').useForNull("").join(index);
            cell.setCellValue(variablesValue);
        }
    }

    for (int i = 0; i < 8; i++) {
        sheet.autoSizeColumn(i, false);
    }
}