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.betaconceptframework.astroboa.commons.excelbuilder.ExcelSheetBuilder.java

License:Open Source License

private void autoSizeColumns(Sheet sheet) {

    for (short columnIndex = 1; columnIndex <= propertyPaths.size(); ++columnIndex) {
        sheet.autoSizeColumn(columnIndex);
    }/*from ww w .  ja v  a  2 s  . c o m*/
}

From source file:org.cgiar.ccafs.ap.summaries.projects.xlsx.BaseXLS.java

License:Open Source License

/**
 * This method writes the headers into the given sheet.
 * /* w w  w . j  a va2  s.  c  om*/
 * @param sheet is the sheet where you want to write the header.
 * @param headers is the array of headers to write.
 */
public void writeHeaders(Sheet sheet, String[] headers) {
    if (usingTemplate) {
        // Row
        Row row = sheet.createRow(rowStart - 1);
        row.setHeightInPoints(HEADER_ROW_HEIGHT);

        // Writing headers.
        Cell cell;
        int counter;
        for (counter = 1; counter <= headers.length; counter++) {
            cell = row.createCell(counter);
            cell.setCellStyle(styleHeader);
            cell.setCellValue(headers[counter - 1]);
            sheet.autoSizeColumn(counter);
        }
    } else {
    }
}

From source file:org.cgiar.ccafs.ap.summaries.projects.xlsx.LeadInstitutionPartnersSummaryXLS.java

License:Open Source License

/**
 * This method is used to generate the csv file for the ProjectLeading institutions.
 * /*w w  w.  j  a  v a  2  s .  c  o  m*/
 * @param projectPartnerInstitutions is the list of institutions to be added
 * @param projectList is the list with the projects related to each institution
 * @return a byte array with the information provided for the xls file.
 */
public byte[] generateXLS(List<Map<String, Object>> projectLeadingInstitutions) {

    try {

        String[] headers = new String[] { "Institution name", "Institution acronym", "Web site",
                "Country location", "Projects" };

        int[] headerTypes = { BaseXLS.COLUMN_TYPE_TEXT_LONG, BaseXLS.COLUMN_TYPE_TEXT_SHORT,
                BaseXLS.COLUMN_TYPE_TEXT_LONG, BaseXLS.COLUMN_TYPE_TEXT_SHORT, BaseXLS.COLUMN_TYPE_TEXT_LONG };

        Workbook workbook = xls.initializeWorkbook(true);
        workbook.setSheetName(0, "  Institutions leading projects");
        Sheet sheet = workbook.getSheetAt(0);

        xls.initializeSheet(sheet, headerTypes);
        xls.writeTitleBox(sheet, "  CCAFS Institutions leading projects");
        xls.writeHeaders(sheet, headers);

        this.addContent(sheet, projectLeadingInstitutions);
        sheet.autoSizeColumn(3);
        // Adding CCAFS logo
        xls.createLogo(workbook, sheet);
        // Set description
        xls.writeDescription(sheet, xls.getText("summaries.leadInstitutionParters.summary.description"));
        xls.writeWorkbook();
        byte[] byteArray = xls.getBytes();
        // Closing streams.
        xls.closeStreams();

        return byteArray;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.cgiar.ccafs.ap.summaries.projects.xlsx.LeadProjectPartnersSummaryXLS.java

License:Open Source License

/**
 * This method is used to generate the xls file for the ProjectLeading institutions.
 * //  w  w  w.j a  v  a  2  s  . c  om
 * @param projectList is the list with the projects partner leaders
 * @return a byte array with the information provided for the xls file.
 */
public byte[] generateXLS(List<Map<String, Object>> projectList) {

    try {

        // Defining headers
        String[] headers = new String[] { "Project Id", "Start date", "End date", "Title", "Type", "Summary",
                "Flagship(s)", "Region(s)", "Lead institution", "Leader", "Coordinator", "Total budget W1/W2",
                "Total budget W3/Bilateral" };

        // Defining header types
        int[] headerTypes = { BaseXLS.COLUMN_TYPE_NUMERIC, BaseXLS.COLUMN_TYPE_DATE, BaseXLS.COLUMN_TYPE_DATE,
                BaseXLS.COLUMN_TYPE_TEXT_LONG, BaseXLS.COLUMN_TYPE_TEXT_SHORT, BaseXLS.COLUMN_TYPE_TEXT_LONG,
                BaseXLS.COLUMN_TYPE_TEXT_SHORT, BaseXLS.COLUMN_TYPE_TEXT_SHORT, BaseXLS.COLUMN_TYPE_TEXT_LONG,
                BaseXLS.COLUMN_TYPE_TEXT_LONG, BaseXLS.COLUMN_TYPE_TEXT_LONG, BaseXLS.COLUMN_TYPE_BUDGET,
                BaseXLS.COLUMN_TYPE_BUDGET };

        Workbook workbook = xls.initializeWorkbook(true);

        workbook.setSheetName(0, "Project leaders");
        Sheet sheet = workbook.getSheetAt(0);
        xls.initializeSheet(sheet, headerTypes);
        xls.writeTitleBox(sheet, " CCAFS Project leaders");
        xls.writeHeaders(sheet, headers);

        this.addContent(sheet, projectList);
        sheet.autoSizeColumn(5);
        // Adding CCAFS logo
        xls.createLogo(workbook, sheet);
        // Set description
        xls.writeDescription(sheet, xls.getText("summaries.leadProjectPartners.summary.description"));
        xls.writeWorkbook();
        byte[] byteArray = xls.getBytes();
        // Closing streams.
        xls.closeStreams();

        return byteArray;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.cgiar.ccafs.ap.summaries.projects.xlsx.NoLoggedInPartnersSummaryXLS.java

License:Open Source License

/**
 * This method is used to generate the xls file for the partners not having logged in P&R.
 * //from   w w  w.  j  a va 2  s. c  o  m
 * @param PartnersInformation is the list of partners to be added
 */
public byte[] generateXLS(List<Map<String, Object>> PartnersInformation) {

    try {

        // Writting headers
        String[] headers = new String[] { "ID", "Name", "Email", "Contact Type", "Related Project Ids", };

        // Writting style content
        int[] headersType = new int[] { BaseXLS.COLUMN_TYPE_NUMERIC, BaseXLS.COLUMN_TYPE_TEXT_SHORT,
                BaseXLS.COLUMN_TYPE_TEXT_SHORT, BaseXLS.COLUMN_TYPE_TEXT_SHORT, BaseXLS.COLUMN_TYPE_TEXT_LONG };

        Workbook workbook = xls.initializeWorkbook(true);

        // renaming sheet
        workbook.setSheetName(0, "Partners not logged in");
        Sheet sheet = workbook.getSheetAt(0);

        xls.initializeSheet(sheet, headersType);

        // Writing the sheet in the yellow box
        xls.writeTitleBox(sheet, xls.getText("summaries.partners.notlogged.summary.name"));

        // Writing the sheet in the yellow box
        xls.writeDescription(sheet, xls.getText("summaries.partners.notlogged.summary.description"));

        // write text box
        xls.createLogo(workbook, sheet);

        xls.writeHeaders(sheet, headers);

        this.addContent(PartnersInformation, sheet);
        sheet.autoSizeColumn(1);

        // this.flush();
        xls.writeWorkbook();

        byte[] byteArray = xls.getBytes();

        // Closing streams.
        xls.closeStreams();

        return byteArray;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.dashbuilder.dataset.backend.DataSetBackendServicesImpl.java

License:Apache License

@Override
public String exportDataSetExcel(DataSet dataSet) {
    // TODO?: Excel 2010 limits: 1,048,576 rows by 16,384 columns; row width 255 characters
    if (dataSet == null)
        throw new IllegalArgumentException("Null dataSet specified!");
    int columnCount = dataSet.getColumns().size();
    int rowCount = dataSet.getRowCount() + 1; //Include header row;
    int row = 0;//w w  w  . j a va 2s  .  c  o 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(dataSet.getColumnByIndex(i).getId());
    }

    // 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 = dataSet.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).getName());
            } 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);
    }

    Path tempExcelFilePath = null;
    try {
        tempExcelFilePath = ioService.createTempFile("export", "xlsx", null);
        OutputStream os = Files.newOutputStream(tempExcelFilePath);
        wb.write(os);
        os.flush();
        os.close();
    } catch (Exception e) {
        log.error("Error in excel export: ", 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 tempExcelFilePath.toString();
}

From source file:org.dashbuilder.dataset.backend.DataSetExportServicesImpl.java

License:Apache License

@Override
public org.uberfire.backend.vfs.Path exportDataSetExcel(DataSet dataSet) {
    try {//from  w  w w  .jav  a2s  .  co  m
        // TODO?: Excel 2010 limits: 1,048,576 rows by 16,384 columns; row width 255 characters
        if (dataSet == null)
            throw new IllegalArgumentException("Null dataSet specified!");
        int columnCount = dataSet.getColumns().size();
        int rowCount = dataSet.getRowCount() + 1; //Include header row;
        int row = 0;

        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(dataSet.getColumnByIndex(i).getId());
        }

        // 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 = dataSet.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).getName());
                } 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);
        }

        String tempXlsFile = uuidGenerator.newUuid() + ".xlsx";
        Path tempXlsPath = gitStorage.createTempFile(tempXlsFile);
        OutputStream os = Files.newOutputStream(tempXlsPath);
        wb.write(os);
        os.flush();
        os.close();

        // 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 Paths.convert(tempXlsPath);
    } catch (Exception e) {
        throw exceptionManager.handleException(e);
    }
}

From source file:org.databene.formats.xls.XLSUtil.java

License:Open Source License

public static void autoSizeColumns(Workbook workbook) {
    int sheetCount = workbook.getNumberOfSheets();
    for (int i = 0; i < sheetCount; i++) {
        Sheet sheet = workbook.getSheetAt(i);
        int firstRowNum = sheet.getFirstRowNum();
        if (firstRowNum >= 0) {
            Row firstRow = sheet.getRow(firstRowNum);
            for (int cellnum = firstRow.getFirstCellNum(); cellnum < firstRow.getLastCellNum(); cellnum++)
                sheet.autoSizeColumn(cellnum);
        }/*from   w w  w.j a v a 2 s. c o  m*/
    }
}

From source file:org.eclipse.rcptt.ecl.data.apache.poi.impl.internal.commands.WriteExcelFileService.java

License:Open Source License

private void autoSizeColumns(Sheet sheet) {
    int length = sheet.getRow(0).getLastCellNum();
    if (length == -1) {
        return;/* w  w  w.j av  a 2 s .c  o m*/
    }
    for (int col = 0; col < length; col++) {
        sheet.autoSizeColumn(col);
    }
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

private static void writeStyleAfterFinish(boolean useTemplate, Sheet sheet,
        ExcelWriteSheetProcessor<?> sheetProcessor) {
    if (useTemplate) {
        return;//w w w .jav a 2s  . com
    }
    ExcelWriteFieldMapping excelWriteFieldMapping = sheetProcessor.getFieldMapping();
    if (excelWriteFieldMapping == null) {
        return;
    }
    Map<String, Map<Integer, ExcelWriteFieldMappingAttribute>> mme = excelWriteFieldMapping.export();
    if (mme == null) {
        return;
    }
    for (Map.Entry<String, Map<Integer, ExcelWriteFieldMappingAttribute>> entry : mme.entrySet()) {
        Map<Integer, ExcelWriteFieldMappingAttribute> me = entry.getValue();
        for (Integer column : me.keySet()) {
            sheet.autoSizeColumn(column);
        }
    }
}