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);

Source Link

Document

Adjusts the column width to fit the contents.

Usage

From source file:org.isisaddons.module.excel.dom.ExcelConverter.java

License:Apache License

@SuppressWarnings("unused")
private void autoSize(final Sheet sh, final int numProps) {
    for (int prop = 0; prop < numProps; prop++) {
        sh.autoSizeColumn(prop);
    }//ww w . j a  va 2s  .com
}

From source file:org.isisaddons.wicket.excel.cpt.ui.ExcelFileModel.java

License:Apache License

protected void autoSize(final Sheet sh, int numProps) {
    for (int prop = 0; prop < numProps; prop++) {
        sh.autoSizeColumn(prop);
    }/*from   w ww.j  a v a2 s  .com*/
}

From source file:org.jaffa.qm.finder.apis.ExcelExportService.java

License:Open Source License

public static Workbook generateExcel(QueryServiceConfig master, QueryServiceConfig child, String sheetName)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {

    Workbook wb = null;// ww  w  .  ja va  2  s.co  m
    String legacyExport = (String) ContextManagerFactory.instance()
            .getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {
        wb = new SXSSFWorkbook(100);
    }
    try {
        // Creating worksheet
        Sheet sheet = null;
        if (sheetName != null)
            sheet = wb.createSheet(sheetName);
        else
            sheet = wb.createSheet();

        // creating a custom palette for the workbook
        CellStyle style = wb.createCellStyle();
        style = wb.createCellStyle();

        // setting the foreground color to gray
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Setting the border for the cells
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setAlignment(CellStyle.ALIGN_CENTER);

        // setting font weight
        Font titleFont = wb.createFont();
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);

        int rowNum = 0;
        Row headerRow = sheet.createRow(rowNum);
        int colIndex = 0;
        for (Object o : master.getColumnModel()) {
            String columnTitle = (String) ((DynaBean) o).get("header");
            if (columnTitle == null || columnTitle.length() == 0)
                columnTitle = (String) ((DynaBean) o).get("mapping");

            headerRow.createCell(colIndex).setCellValue(columnTitle);
            Cell cell = headerRow.getCell(colIndex);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(colIndex);
            colIndex += 1;
        }

        // Generate the Excel output by creating a simple HTML table
        if (child != null) {
            for (Object o : child.getColumnModel()) {
                String columnTitle = (String) ((DynaBean) o).get("header");
                if (columnTitle == null || columnTitle.length() == 0)
                    columnTitle = (String) ((DynaBean) o).get("mapping");

                headerRow.createCell(colIndex).setCellValue(columnTitle);
                Cell cell = headerRow.getCell(colIndex);
                cell.setCellStyle(style);
                sheet.autoSizeColumn(colIndex);
                colIndex += 1;

            }
        }

        // Invoke the query and obtain an array of Graph objects
        Object[] queryOutput = invokeQueryService(master.getCriteriaClassName(), master.getCriteriaObject(),
                master.getServiceClassName(), master.getServiceClassMethodName());

        // Add the data rows
        if (queryOutput != null) {
            for (Object row : queryOutput) {
                Object[] detailQueryOutput = new Object[0];
                if (child == null) {
                    rowNum += 1;
                    Row dataRow = sheet.createRow((short) rowNum);
                    int colNum = 0;
                    // extract the columns from master object
                    for (Object o : master.getColumnModel()) {
                        String mapping = (String) ((DynaBean) o).get("mapping");
                        Object value = null;
                        if (mapping.startsWith("appFields.")) {
                            mapping = mapping.substring(10);
                            try {
                                Object[] appFields = (Object[]) PropertyUtils.getProperty(row,
                                        "applicationFields");
                                for (Object field : appFields) {
                                    String name = (String) PropertyUtils.getProperty(field, "name");
                                    if (name.equals(mapping)) {
                                        value = (String) PropertyUtils.getProperty(field, "value");
                                    }
                                }
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Property not found: " + mapping, e);
                            }
                        } else {
                            try {
                                value = PropertyUtils.getProperty(row, mapping);
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Property not found: " + mapping, e);
                            }
                        }
                        dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                        colNum += 1;
                    }
                } else { //child is not null
                    // load the child rows
                    String detailCriteriaObject = child.getCriteriaObject();
                    for (int i = 0; i < child.getMasterKeyFieldNames().length; i++) {
                        String kfn = child.getMasterKeyFieldNames()[i];
                        try {
                            String keyValue = (String) PropertyUtils.getProperty(row, kfn);
                            detailCriteriaObject = detailCriteriaObject.replace("{" + i + "}", keyValue);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Key property not found: " + kfn, e);
                        }
                    }
                    detailQueryOutput = invokeQueryService(child.getCriteriaClassName(), detailCriteriaObject,
                            child.getServiceClassName(), "query");

                    // add the child columns
                    if (detailQueryOutput != null && detailQueryOutput.length > 0) {
                        for (Object detailRow : detailQueryOutput) {
                            rowNum += 1;
                            Row dataRow = sheet.createRow((short) rowNum);

                            int colNum = 0;
                            // extract the columns from master object
                            for (Object obj : master.getColumnModel()) {
                                String masterMapping = (String) ((DynaBean) obj).get("mapping");
                                Object masterValue = null;
                                try {
                                    masterValue = PropertyUtils.getProperty(row, masterMapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found: " + masterMapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(masterValue, (DynaBean) obj));
                                colNum += 1;
                            }

                            for (Object o : child.getColumnModel()) {
                                String mapping = (String) ((DynaBean) o).get("mapping");
                                Object value = null;
                                try {
                                    value = PropertyUtils.getProperty(detailRow, mapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found in child result: " + mapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                                colNum += 1;
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return wb;
}

From source file:org.jaffa.ria.finder.apis.ExcelExportService.java

License:Open Source License

public static Workbook generateExcel(QueryServiceConfig master, QueryServiceConfig child, String sheetName)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {

    Workbook wb = null;/* w  ww .  j av  a  2  s .  co  m*/
    String legacyExport = (String) ContextManagerFactory.instance()
            .getProperty("jaffa.widgets.exportToExcel.legacy");
    if (legacyExport != null && legacyExport.equals("T")) {
        wb = new HSSFWorkbook();
    } else {
        wb = new SXSSFWorkbook(100);
    }
    try {
        // Creating worksheet
        Sheet sheet = null;
        if (sheetName != null) {
            if (sheetName.length() > 31)
                sheetName = sheetName.substring(0, 31);
            char replaceChar = '_';
            sheetName = sheetName.replace('\u0003', replaceChar).replace(':', replaceChar)
                    .replace('/', replaceChar).replace("\\\\", Character.toString(replaceChar))
                    .replace('?', replaceChar).replace('*', replaceChar).replace(']', replaceChar)
                    .replace('[', replaceChar);
            sheet = wb.createSheet(sheetName);
        } else
            sheet = wb.createSheet();

        // creating a custom palette for the workbook
        CellStyle style = wb.createCellStyle();
        style = wb.createCellStyle();

        // setting the foreground color to gray
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // Setting the border for the cells
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setAlignment(CellStyle.ALIGN_CENTER);

        // setting font weight
        Font titleFont = wb.createFont();
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);

        int rowNum = 0;
        Row headerRow = sheet.createRow(rowNum);
        int colIndex = 0;
        for (Object o : master.getColumnModel()) {
            String columnTitle = (String) ((DynaBean) o).get("header");
            if (columnTitle == null || columnTitle.length() == 0)
                columnTitle = (String) ((DynaBean) o).get("mapping");

            headerRow.createCell(colIndex).setCellValue(columnTitle);
            Cell cell = headerRow.getCell(colIndex);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(colIndex);
            colIndex += 1;
        }

        // Generate the Excel output by creating a simple HTML table
        if (child != null) {
            for (Object o : child.getColumnModel()) {
                String columnTitle = (String) ((DynaBean) o).get("header");
                if (columnTitle == null || columnTitle.length() == 0)
                    columnTitle = (String) ((DynaBean) o).get("mapping");

                headerRow.createCell(colIndex).setCellValue(columnTitle);
                Cell cell = headerRow.getCell(colIndex);
                cell.setCellStyle(style);
                sheet.autoSizeColumn(colIndex);
                colIndex += 1;

            }
        }

        // Invoke the query and obtain an array of Graph objects
        Object[] queryOutput = invokeQueryService(master.getCriteriaClassName(), master.getCriteriaObject(),
                master.getServiceClassName(), master.getServiceClassMethodName());

        // Add the data rows
        if (queryOutput != null) {
            for (Object row : queryOutput) {
                Object[] detailQueryOutput = new Object[0];
                if (child == null) {
                    rowNum += 1;
                    Row dataRow = sheet.createRow((short) rowNum);
                    int colNum = 0;
                    // extract the columns from master object
                    for (Object o : master.getColumnModel()) {
                        String mapping = (String) ((DynaBean) o).get("mapping");
                        Object value = null;
                        try {
                            value = PropertyUtils.getProperty(row, mapping);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Property not found: " + mapping, e);
                        }

                        dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                        colNum += 1;
                    }
                } else { //child is not null
                    // load the child rows
                    String detailCriteriaObject = child.getCriteriaObject();
                    for (int i = 0; i < child.getMasterKeyFieldNames().length; i++) {
                        String kfn = child.getMasterKeyFieldNames()[i];
                        try {
                            String keyValue = (String) PropertyUtils.getProperty(row, kfn);
                            detailCriteriaObject = detailCriteriaObject.replace("{" + i + "}", keyValue);
                        } catch (Exception e) {
                            if (log.isDebugEnabled())
                                log.debug("Key property not found: " + kfn, e);
                        }
                    }
                    detailQueryOutput = invokeQueryService(child.getCriteriaClassName(), detailCriteriaObject,
                            child.getServiceClassName(), "query");

                    // add the child columns
                    if (detailQueryOutput != null && detailQueryOutput.length > 0) {
                        for (Object detailRow : detailQueryOutput) {
                            rowNum += 1;
                            Row dataRow = sheet.createRow((short) rowNum);

                            int colNum = 0;
                            // extract the columns from master object
                            for (Object obj : master.getColumnModel()) {
                                String masterMapping = (String) ((DynaBean) obj).get("mapping");
                                Object masterValue = null;
                                try {
                                    masterValue = PropertyUtils.getProperty(row, masterMapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found: " + masterMapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(masterValue, (DynaBean) obj));
                                colNum += 1;
                            }

                            for (Object o : child.getColumnModel()) {
                                String mapping = (String) ((DynaBean) o).get("mapping");
                                Object value = null;
                                try {
                                    value = PropertyUtils.getProperty(detailRow, mapping);
                                } catch (Exception e) {
                                    if (log.isDebugEnabled())
                                        log.debug("Property not found in child result: " + mapping, e);
                                }

                                dataRow.createCell(colNum).setCellValue(format(value, (DynaBean) o));
                                colNum += 1;
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return wb;
}

From source file:org.jboss.dashboard.displayer.table.ExportTool.java

License:Apache License

public InputStream exportExcel(Table table) {
    // TODO?: Excel 2010 limits: 1,048,576 rows by 16,384 columns; row width 255 characters
    if (table == null)
        throw new IllegalArgumentException("Null table specified!");
    int columnCount = table.getColumnCount();
    int rowCount = table.getRowCount() + 1; //Include header row
    int row = 0;//from   w ww .  j  av  a 2  s  . co  m

    SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sh = wb.createSheet("Sheet 1");

    // General setup
    sh.setDisplayGridlines(true);
    sh.setPrintGridlines(false);
    sh.setFitToPage(true);
    sh.setHorizontallyCenter(true);
    PrintSetup printSetup = sh.getPrintSetup();
    printSetup.setLandscape(true);

    // Create header
    Row header = sh.createRow(row++);
    header.setHeightInPoints(20f);
    for (int i = 0; i < columnCount; i++) {
        Cell cell = header.createCell(i);
        cell.setCellStyle(styles.get("header"));
        cell.setCellValue(table.getColumnName(i));
    }

    // Create data rows
    for (; row < rowCount; row++) {
        Row _row = sh.createRow(row);
        for (int cellnum = 0; cellnum < columnCount; cellnum++) {
            Cell cell = _row.createCell(cellnum);
            Object value = table.getValueAt(row - 1, cellnum);
            if (value instanceof Short || value instanceof Long || value instanceof Integer
                    || value instanceof BigInteger) {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                cell.setCellStyle(styles.get("integer_number_cell"));
                cell.setCellValue(((Number) value).doubleValue());
            } else if (value instanceof Float || value instanceof Double || value instanceof BigDecimal) {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                cell.setCellStyle(styles.get("decimal_number_cell"));
                cell.setCellValue(((Number) value).doubleValue());
            } else if (value instanceof Date) {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(styles.get("date_cell"));
                cell.setCellValue((Date) value);
            } else if (value instanceof Interval) {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(styles.get("text_cell"));
                cell.setCellValue(((Interval) value).getDescription(LocaleManager.currentLocale()));
            } else if (value == null) {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(styles.get("text_cell"));
                cell.setCellValue("");
            } else {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                cell.setCellStyle(styles.get("text_cell"));
                cell.setCellValue(value.toString());
            }
        }
    }

    // Adjust column size
    for (int i = 0; i < columnCount; i++) {
        sh.autoSizeColumn(i);
    }

    ByteArrayInputStream bis = null;
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wb.write(bos);
        bis = new ByteArrayInputStream(bos.toByteArray());
        bos.close();
    } catch (IOException e) {
        log.error("Data export error: ", e);
    }

    // Dispose of temporary files backing this workbook on disk
    if (!wb.dispose())
        log.warn("Could not dispose of temporary file associated to data export!");

    return bis;
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.cliente.GeneradorReporteImp.java

License:Apache License

@Override
public void generaReporte(ParametrosReporte param) {
    FileOutputStream fileOut = null;
    ReporteCliente datos = datosReporteClienteFactory.getData();
    try {//from www. j  a v a  2 s. c  om
        GeneradorReporteImp.LOGGER.info("file:" + param.getDestination());
        //Workbook wb = WorkbookFactory.create(template);
        XSSFWorkbook wb = new XSSFWorkbook();
        int maxColumn = 0;
        //CreationHelper createHelper = wb.getCreationHelper();
        //se crea la primera hoja
        Sheet sheet = wb.createSheet("Hoja1");
        BordeSeccion borde = new BordeSeccion();
        ContextoSeccion contexto = new ContextoSeccion();
        contexto.setWb(wb);
        contexto.setSheet(sheet);
        //encabezado
        borde.setLeftColumn(1);
        borde.setUpperRow(1);
        BordeSeccion bordeEncabezado = encabezadoReporteCliente.generar(borde, contexto, datos);
        if (bordeEncabezado.getRightColumn() > maxColumn) {
            maxColumn = bordeEncabezado.getRightColumn();
        }
        //datos auto
        borde.setLeftColumn(1);
        borde.setUpperRow(bordeEncabezado.getLowerRow() + 2);
        BordeSeccion bordeAuto = datosAutoReporteCliente.generar(borde, contexto, datos);
        if (bordeAuto.getRightColumn() > maxColumn) {
            maxColumn = bordeAuto.getRightColumn();
        }
        //mecanica
        borde.setLeftColumn(1);
        borde.setUpperRow(bordeAuto.getLowerRow() + 2);
        BordeSeccion bordeMecanica = costoMecanicaReporteCliente.generar(borde, contexto, datos);
        if (bordeMecanica.getRightColumn() > maxColumn) {
            maxColumn = bordeMecanica.getRightColumn();
        }
        //hojalateria
        borde.setLeftColumn(bordeMecanica.getRightColumn() + 1);
        BordeSeccion bordeHojalateria = costoHojalateriaReporteCliente.generar(borde, contexto, datos);
        if (bordeHojalateria.getRightColumn() > maxColumn) {
            maxColumn = bordeHojalateria.getRightColumn();
        }
        //total servicio
        if (bordeMecanica.getLowerRow() < bordeHojalateria.getLowerRow()) {
            borde.setUpperRow(bordeHojalateria.getLowerRow() + 2);
        } else {
            borde.setUpperRow(bordeMecanica.getLowerRow() + 2);
        }
        borde.setLeftColumn(1);
        BordeSeccion bordeTotalServicio = totalServicioReporteCliente.generar(borde, contexto, datos);
        if (bordeTotalServicio.getRightColumn() > maxColumn) {
            maxColumn = bordeTotalServicio.getRightColumn();
        }
        //bitacora
        borde.setLeftColumn(1);
        borde.setUpperRow(bordeTotalServicio.getLowerRow() + 3);
        BordeSeccion bordeBitacora = bitacoraReporteCliente.generar(borde, contexto, datos);
        if (bordeBitacora.getRightColumn() > maxColumn) {
            maxColumn = bordeBitacora.getRightColumn();
        }
        for (int i = 1; i <= maxColumn; i++) {
            sheet.autoSizeColumn(i);
        }
        fileOut = new FileOutputStream(param.getDestination());
        wb.write(fileOut);
        fileOut.close();
    } catch (Exception ex) {
        GeneradorReporteImp.LOGGER.error("error al generar reporte", ex);
    } finally {
        try {
            fileOut.close();
        } catch (IOException | NullPointerException ex) {
            GeneradorReporteImp.LOGGER.error("error al cerrar archivo de reporte", ex);
        }
    }
}

From source file:org.patientview.radar.service.impl.ExcelDocumentDataBuilder.java

License:Open Source License

public byte[] build(DocumentData documentData) {

    Workbook workbook = new HSSFWorkbook();
    CreationHelper createHelper = workbook.getCreationHelper();
    Sheet sheet = workbook.createSheet("data");

    // add the headers/columns
    Row headerRow = sheet.createRow((short) 0);
    sheet.autoSizeColumn(0);

    CellStyle headerStyle = workbook.createCellStyle();

    headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    headerStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    headerStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
    headerStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
    headerStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());

    headerStyle.setLeftBorderColor(CellStyle.BORDER_THIN);
    headerStyle.setRightBorderColor(CellStyle.BORDER_THIN);
    headerStyle.setTopBorderColor(CellStyle.BORDER_THIN);
    headerStyle.setBottomBorderColor(CellStyle.BORDER_THIN);

    Font headerFont = workbook.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerStyle.setFont(headerFont);//  w  w  w .j  a  v a  2s. co  m

    List<String> headers = documentData.getHeaders();
    int headerColumnIndex = 0;
    for (String header : headers) {
        sheet.autoSizeColumn(headerColumnIndex);
        Cell cell = headerRow.createCell(headerColumnIndex);
        cell.setCellStyle(headerStyle);
        cell.setCellValue(header);
        headerColumnIndex++;
    }

    // add the row data
    int columnIndex = 0;
    int rowIndex = 1;
    for (List<String> row : documentData.getRows()) {
        Row spreadSheetRow = sheet.createRow((short) rowIndex++);
        for (String data : row) {
            spreadSheetRow.createCell(columnIndex++).setCellValue(data);
        }
        columnIndex = 0;
    }

    // set the column width to fit the contents - this must be done after the data is added
    headerColumnIndex = 0;
    for (String header : headers) {
        sheet.autoSizeColumn(headerColumnIndex);
        headerColumnIndex++;
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        workbook.write(outputStream);
        outputStream.close();
        outputStream.flush();
    } catch (IOException e) {
        LOGGER.error("Unable to write workbook to output stream " + e.getMessage(), e);
    }

    return outputStream.toByteArray();
}

From source file:org.phenotips.export.internal.SpreadsheetExporter.java

License:Open Source License

protected void write(DataSection section, Sheet sheet) {
    DataCell[][] cells = section.getMatrix();
    Styler styler = new Styler();

    Row row;//  www.java 2s  . c  o  m
    for (Integer y = 0; y <= section.getMaxY(); y++) {
        row = sheet.createRow(y);
        Integer maxLines = 0;

        for (Integer x = 0; x <= section.getMaxX(); x++) {
            DataCell dataCell = cells[x][y];
            if (dataCell == null) {
                continue;
            }
            Cell cell = row.createCell(x);
            cell.setCellValue(dataCell.getValue());
            styler.style(dataCell, cell, this.wBook);

            if (dataCell.getNumberOfLines() != null) {
                maxLines = maxLines < dataCell.getNumberOfLines() ? dataCell.getNumberOfLines() : maxLines;
            }
        }
        if (maxLines > 1) {
            Integer height = maxLines * 400;
            row.setHeight(height.shortValue());
        }
    }
    for (int col = 0; section.getMaxX() >= col; col++) {
        sheet.autoSizeColumn(col);
        if (sheet.getColumnWidth(col) > (DataToCellConverter.charactersPerLine * 210)) {
            sheet.setColumnWidth(col, DataToCellConverter.charactersPerLine * 210);
        }
    }

    /** Merging has to be done after autosizing because otherwise autosizing breaks */
    for (Integer y = 0; y <= section.getMaxY(); y++) {
        for (Integer x = 0; x <= section.getMaxX(); x++) {
            DataCell dataCell = cells[x][y];
            if (dataCell != null && dataCell.getMergeX() != null) {
                sheet.addMergedRegion(new CellRangeAddress(y, y, x, x + dataCell.getMergeX()));
            }
            /*
             * No longer will be merging cells on the Y axis, but keep this code for future reference. if
             * (dataCell.getYBoundry() != null) { sheet.addMergedRegion(new CellRangeAddress(dataCell.y,
             * dataCell.getYBoundry(), dataCell.x, dataCell.x)); }
             */
        }
    }
}

From source file:org.primefaces.component.export.ExcelExporter.java

License:Open Source License

@Override
public void export(FacesContext context, DataTable table, String filename, boolean pageOnly,
        boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, ExporterOptions options) throws IOException {
    Workbook wb = createWorkBook();// www  .ja  v a2 s  . co m
    String sheetName = getSheetName(context, table);
    if (sheetName == null) {
        sheetName = table.getId();
    }

    sheetName = WorkbookUtil.createSafeSheetName(sheetName);
    if (sheetName.equals("empty") || sheetName.equals("null")) {
        sheetName = "Sheet";
    }

    Sheet sheet = wb.createSheet(sheetName);

    if (preProcessor != null) {
        preProcessor.invoke(context.getELContext(), new Object[] { wb });
    }

    applyOptions(wb, table, sheet, options);
    exportTable(context, table, sheet, pageOnly, selectionOnly);

    for (int i = 0; i < table.getColumnsCount(); i++) {
        sheet.autoSizeColumn((short) i);
    }

    if (postProcessor != null) {
        postProcessor.invoke(context.getELContext(), new Object[] { wb });
    }

    writeExcelToResponse(context.getExternalContext(), wb, filename);
}

From source file:org.primefaces.component.export.ExcelExporter.java

License:Open Source License

@Override
public void export(FacesContext context, String filename, List<DataTable> tables, boolean pageOnly,
        boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, ExporterOptions options) throws IOException {
    Workbook wb = createWorkBook();/*www .  j  a v  a2  s .  c om*/

    if (preProcessor != null) {
        preProcessor.invoke(context.getELContext(), new Object[] { wb });
    }

    for (int i = 0; i < tables.size(); i++) {
        DataTable table = tables.get(i);
        String sheetName = getSheetName(context, table);
        if (sheetName == null) {
            sheetName = table.getId();
        }

        sheetName = WorkbookUtil.createSafeSheetName(sheetName);
        if (sheetName.equals("empty") || sheetName.equals("null")) {
            sheetName = "Sheet" + String.valueOf(i + 1);
        }

        Sheet sheet = wb.createSheet(sheetName);
        applyOptions(wb, table, sheet, options);
        exportTable(context, table, sheet, pageOnly, selectionOnly);

        for (int j = 0; j < table.getColumnsCount(); j++) {
            sheet.autoSizeColumn((short) j);
        }
    }

    if (postProcessor != null) {
        postProcessor.invoke(context.getELContext(), new Object[] { wb });
    }

    writeExcelToResponse(context.getExternalContext(), wb, filename);
}