Example usage for org.apache.poi.ss.usermodel PrintSetup setLandscape

List of usage examples for org.apache.poi.ss.usermodel PrintSetup setLandscape

Introduction

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

Prototype

void setLandscape(boolean ls);

Source Link

Document

Set whether to print in landscape

Usage

From source file:nz.ac.auckland.abi.formatting.poi.ModelJSONToExcel.java

License:LGPL

private void addWorkSheet(Workbook wb, String measure, List<FEMModelMeasure> measures, int maxTimePoints,
        Map<String, CellStyle> styles) {
    Sheet sheet = wb.createSheet(measure);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setHorizontallyCenter(true);//from  w  w  w  .  j  a v  a  2s  . c  o m

    final int leadingHeaders = 4;
    int rowCounter = 0;
    // Create header row
    Row headerRow = sheet.createRow(rowCounter++);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    int colCtr = 0;
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("ModelName");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("StartTime");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("EndTime");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MetaData");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("ID");
        headerCell.setCellStyle(styles.get("header"));
    }
    // Insert Time points
    for (int i = 0; i < maxTimePoints; i++) {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("" + i);
        headerCell.setCellStyle(styles.get("header"));
    }
    // Insert composite variables
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MAX");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MIN");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("MEAN");
        headerCell.setCellStyle(styles.get("header"));
    }
    {
        headerCell = headerRow.createCell(colCtr++);
        headerCell.setCellValue("SD");
        headerCell.setCellStyle(styles.get("header"));
    }
    // Output the values for each measure

    for (FEMModelMeasure mes : measures) {
        double[][] strains = mes.getMeasure(measure);
        if (strains == null)
            continue;
        int numRows = strains.length + 1; // 1 for Avg
        int rowStarts = rowCounter;
        int colCounter = 0;
        for (int rctr = 0; rctr < numRows - 1; rctr++) {
            colCounter = 0;
            int myRowID = rowCounter + 1;
            Row row = sheet.createRow(rowCounter++);
            for (int colc = 0; colc < leadingHeaders; colc++) { // Common
                // Elements
                row.createCell(colCounter++);
            }
            // Create ROW ID
            {
                Cell cell = row.createCell(colCounter++);
                cell.setCellValue("S" + (rctr + 1));
            }
            String strainStartXLColName = getColumnPrefix(colCounter);
            int strainLength = strains[rctr].length;
            for (int stc = 0; stc < strainLength; stc++) {
                Cell cell = row.createCell(colCounter++);
                cell.setCellValue(strains[rctr][stc]);
            }
            String strainEndXLColName = getColumnPrefix(colCounter - 1);
            while (strainLength < maxTimePoints) { // Create dummy cells to
                // fill up space
                row.createCell(colCounter++);
                strainLength++;
            }
            // Add formulas and create names
            {
                //String modelName = mes.getModelName();
                //String sname = "";
                // MAX
                Cell cell = row.createCell(colCounter++);
                String ref = strainStartXLColName + "" + myRowID + ":" + strainEndXLColName + "" + myRowID;
                cell.setCellFormula("MAX(" + ref + ")");
                cell.setCellStyle(styles.get("MAX"));
                /*
                 * sname =
                 * (modelName+"_"+measure+"_"+"MAX_S"+(rctr+1)..replaceAll
                 * (" ", "_").trim(); Name namedCel = wb.createName();
                 * namedCel.setNameName(sname); String reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
                // MIN
                cell = row.createCell(colCounter++);
                cell.setCellFormula("MIN(" + ref + ")");
                cell.setCellStyle(styles.get("MIN"));
                /*
                 * sname = modelName+"_"+measure+"_"+"MIN_S"+(rctr+1);
                 * namedCel = wb.createName(); namedCel.setNameName(sname);
                 * reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
                // MEAN
                cell = row.createCell(colCounter++);
                cell.setCellFormula("AVERAGE(" + ref + ")");
                cell.setCellStyle(styles.get("AVERAGE"));
                /*
                 * sname = modelName+"_"+measure+"_"+"AVERAGE_S"+(rctr+1);
                 * namedCel = wb.createName(); namedCel.setNameName(sname);
                 * reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
                // STANDARD DEVIATION
                cell = row.createCell(colCounter++);
                cell.setCellFormula("STDEV(" + ref + ")");
                cell.setCellStyle(styles.get("STDEV"));
                /*
                 * sname = modelName+"_"+measure+"_"+"STDEV_S"+(rctr+1);
                 * namedCel = wb.createName(); namedCel.setNameName(sname);
                 * reference =
                 * measure+"!"+getColumnPrefix(colCounter-1)+""+myRowID; //
                 * cell reference namedCel.setRefersToFormula(reference);
                 */
            }
        }

        // Add user defined series
        Hashtable<String, String> formulaMap = new Hashtable<String, String>();
        for (String exp : userSeries) {

            // Replace all S[0-9]*, and D[0-9]* with appropriate column
            // values
            String toks[] = exp.split("=");
            int myRowID = rowCounter;
            colCounter = 0;
            Row row = sheet.createRow(rowCounter++);
            for (int colc = 0; colc < leadingHeaders; colc++) { // Common
                // Elements
                row.createCell(colCounter++);
            }
            // Create ROW ID
            {
                Cell cell = row.createCell(colCounter++);
                cell.setCellValue(toks[0]);
            }
            String strainStartXLColName = getColumnPrefix(colCounter);
            int strainLength = strains[numRows - 2].length;
            for (int stc = 0; stc < strainLength; stc++) {
                Cell cell = row.createCell(colCounter++);
                // Get the expression
                String expression = toks[1].toLowerCase();// Regex is case
                // senstive,
                // since th
                // COLUMN
                // PREFIXs are
                // CAPS,
                // replaceAll
                // will work as
                // expected else
                // S17 will
                // mathc for S1
                // (but not s1)
                for (int sCtr = mes.numSegments; sCtr > 0; sCtr--) {
                    String XLColName = (char) ('A' + stc + leadingHeaders + 1) + "" + (rowStarts + sCtr); // Note
                    // excel
                    // formulas
                    // need
                    // base
                    // 1
                    expression = expression.replaceAll("s" + sCtr + "{1}", XLColName);
                }
                cell.setCellFormula(expression);
                cell.setCellStyle(styles.get("AVGSERIES"));
            }
            String strainEndXLColName = getColumnPrefix(colCounter - 1);
            while (strainLength < maxTimePoints) { // Create dummy cells to
                // fill up space
                row.createCell(colCounter++);
                strainLength++;
            }
            // Add formulas and create names
            {
                StringBuffer formulas = new StringBuffer();

                String modelName = mes.getModelName();
                char c = modelName.charAt(0);
                if (c >= '0' && c <= '9') {
                    modelName = "_" + modelName;
                }
                String measureName = measure.replaceAll("\\(", "_").replaceAll("\\)", "_").replaceAll(" ", "");
                String sname = "";
                // MAX
                Cell cell = row.createCell(colCounter++);
                String ref = strainStartXLColName + myRowID + ":" + strainEndXLColName + myRowID;
                cell.setCellFormula("MAX(" + ref + ")");
                cell.setCellStyle(styles.get("MAX"));
                sname = (modelName + "_" + measureName + "_" + "MAX_" + toks[0]).replaceAll(" ", "_").trim();
                Name namedCel = wb.createName();
                namedCel.setNameName(sname);
                String reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                // reference
                // in
                // xl
                // base
                try {
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference + "#");
                    // MIN
                    cell = row.createCell(colCounter++);
                    cell.setCellFormula("MIN(" + ref + ")");
                    cell.setCellStyle(styles.get("MIN"));
                    sname = (modelName + "_" + measureName + "_" + "MIN_" + toks[0]).replaceAll(" ", "_")
                            .trim();
                    namedCel = wb.createName();
                    namedCel.setNameName(sname);
                    reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                    // reference
                    // in
                    // xl
                    // base
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference + "#");
                    // MEAN
                    cell = row.createCell(colCounter++);
                    cell.setCellFormula("AVERAGE(" + ref + ")");
                    cell.setCellStyle(styles.get("AVERAGE"));
                    sname = (modelName + "_" + measureName + "_" + "AVERAGE_" + toks[0]).replaceAll(" ", "_")
                            .trim();
                    namedCel = wb.createName();
                    namedCel.setNameName(sname);
                    reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                    // reference
                    // in
                    // xl
                    // base
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference + "#");
                    // STANDARD DEVIATION
                    cell = row.createCell(colCounter++);
                    cell.setCellFormula("STDEV(" + ref + ")");
                    cell.setCellStyle(styles.get("STDEV"));
                    sname = (modelName + "_" + measureName + "_" + "STDEV_" + toks[0]).replaceAll(" ", "_")
                            .trim();
                    namedCel = wb.createName();
                    namedCel.setNameName(sname);
                    reference = measureName + "!" + getColumnPrefix(colCounter - 1) + (myRowID + 1); // cell
                    // reference
                    // in
                    // xl
                    // base
                    namedCel.setRefersToFormula(reference);
                    formulas.append(reference);
                    formulaMap.put(toks[0], formulas.toString());
                } catch (Exception exx) {
                    //exx.printStackTrace();
                    System.out.println(exx + " occured for formula " + reference);
                }
            }
        }
        mes.addToFormulaMap(measure, formulaMap);
        // Set the commom columns
        Row row;
        Cell cell;
        row = sheet.getRow(rowStarts);
        cell = row.getCell(0);
        cell.setCellValue(mes.getModelName());
        cell = row.getCell(1);
        cell.setCellValue(mes.getStartTime());
        cell = row.getCell(2);
        cell.setCellValue(mes.getEndTime());
        cell = row.getCell(3);
        cell.setCellValue(mes.getMetaData());
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$" + (rowStarts + 1) + ":$A$" + (rowCounter))); // Since
        // excel
        // number
        // starts
        // from
        // 1
        // but
        // api
        // is
        // 0
        sheet.addMergedRegion(CellRangeAddress.valueOf("$B$" + (rowStarts + 1) + ":$B$" + (rowCounter)));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + (rowStarts + 1) + ":$C$" + (rowCounter)));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$D$" + (rowStarts + 1) + ":$D$" + (rowCounter)));
        sheet.createRow(rowCounter++);// Create Empty row for model break
    }

}

From source file:org.aio.handy.poi.TimesheetDemo.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;//from ww  w.  ja  va 2  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("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    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 = "e:/timesheet.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:org.alfresco.bm.report.XLSXReporter.java

License:Open Source License

/**
 * Create a 'Summary' sheet containing the table of averages
 *//*www.j a va 2s .  c  o m*/
private void createSummarySheet(XSSFWorkbook workbook) throws IOException, NotFoundException {
    DBObject testRunObj = getTestService().getTestRunMetadata(test, run);

    // Create the sheet
    XSSFSheet sheet = workbook.createSheet("Summary");

    // Create the fonts we need
    Font fontBold = workbook.createFont();
    fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD);

    // Create the styles we need
    XSSFCellStyle summaryDataStyle = sheet.getWorkbook().createCellStyle();
    summaryDataStyle.setAlignment(HorizontalAlignment.RIGHT);
    XSSFCellStyle headerStyle = sheet.getWorkbook().createCellStyle();
    headerStyle.setAlignment(HorizontalAlignment.RIGHT);
    headerStyle.setFont(fontBold);

    XSSFRow row = null;
    int rowCount = 0;
    row = sheet.createRow(rowCount++);
    {
        row.getCell(0).setCellValue("Name:");
        row.getCell(0).setCellStyle(headerStyle);
        row.getCell(1).setCellValue(title);
        row.getCell(1).setCellStyle(summaryDataStyle);
    }
    row = sheet.createRow(rowCount++);
    {
        String description = (String) testRunObj.get(FIELD_DESCRIPTION);
        description = description == null ? "" : description;
        row.getCell(0).setCellValue("Description:");
        row.getCell(0).setCellStyle(headerStyle);
        row.getCell(1).setCellValue(description);
        row.getCell(1).setCellStyle(summaryDataStyle);
    }
    row = sheet.createRow(rowCount++);
    {
        row.getCell(0).setCellValue("Progress (%):");
        row.getCell(0).setCellStyle(headerStyle);
        Double progress = (Double) testRunObj.get(FIELD_PROGRESS);
        progress = progress == null ? 0.0 : progress;
        row.getCell(1).setCellValue(progress * 100);
        row.getCell(1).setCellType(XSSFCell.CELL_TYPE_NUMERIC);
        row.getCell(1).setCellStyle(summaryDataStyle);
    }
    row = sheet.createRow(rowCount++);
    {
        row.getCell(0).setCellValue("State:");
        row.getCell(0).setCellStyle(headerStyle);
        String state = (String) testRunObj.get(FIELD_STATE);
        if (state != null) {
            row.getCell(1).setCellValue(state);
            row.getCell(1).setCellStyle(summaryDataStyle);
        }
    }
    row = sheet.createRow(rowCount++);
    {
        row.getCell(0).setCellValue("Started:");
        row.getCell(0).setCellStyle(headerStyle);
        Long time = (Long) testRunObj.get(FIELD_STARTED);
        if (time > 0) {
            row.getCell(1).setCellValue(FastDateFormat
                    .getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM).format(time));
            row.getCell(1).setCellStyle(summaryDataStyle);
        }
    }
    row = sheet.createRow(rowCount++);
    {
        row.getCell(0).setCellValue("Finished:");
        row.getCell(0).setCellStyle(headerStyle);
        Long time = (Long) testRunObj.get(FIELD_COMPLETED);
        if (time > 0) {
            row.getCell(1).setCellValue(FastDateFormat
                    .getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM).format(time));
            row.getCell(1).setCellStyle(summaryDataStyle);
        }
    }
    row = sheet.createRow(rowCount++);
    {
        row.getCell(0).setCellValue("Duration:");
        row.getCell(0).setCellStyle(headerStyle);
        Long time = (Long) testRunObj.get(FIELD_DURATION);
        if (time > 0) {
            row.getCell(1).setCellValue(DurationFormatUtils.formatDurationHMS(time));
            row.getCell(1).setCellStyle(summaryDataStyle);
        }
    }

    rowCount++;
    rowCount++;
    // Create a header row
    row = sheet.createRow(rowCount++); // Header row
    String[] headers = new String[] { "Event Name", "Total Count", "Success Count", "Failure Count",
            "Success Rate (%)", "Min (ms)", "Max (ms)", "Arithmetic Mean (ms)", "Standard Deviation (ms)" };
    int columnCount = 0;
    for (String header : headers) {
        XSSFCell cell = row.getCell(columnCount++);
        cell.setCellStyle(headerStyle);
        cell.setCellValue(header);
    }
    // Grab results and output them
    columnCount = 0;
    TreeMap<String, ResultSummary> summaries = collateResults(true);
    for (Map.Entry<String, ResultSummary> entry : summaries.entrySet()) {
        // Reset column count
        columnCount = 0;

        row = sheet.createRow(rowCount++);
        String eventName = entry.getKey();
        ResultSummary summary = entry.getValue();
        SummaryStatistics statsSuccess = summary.getStats(true);
        SummaryStatistics statsFail = summary.getStats(false);
        // Event Name
        row.getCell(columnCount++).setCellValue(eventName);
        // Total Count
        row.getCell(columnCount++).setCellValue(summary.getTotalResults());
        // Success Count
        row.getCell(columnCount++).setCellValue(statsSuccess.getN());
        // Failure Count
        row.getCell(columnCount++).setCellValue(statsFail.getN());
        // Success Rate (%)
        row.getCell(columnCount++).setCellValue(summary.getSuccessPercentage());
        // Min (ms)
        row.getCell(columnCount++).setCellValue((long) statsSuccess.getMin());
        // Max (ms)
        row.getCell(columnCount++).setCellValue((long) statsSuccess.getMax());
        // Arithmetic Mean (ms)
        row.getCell(columnCount++).setCellValue((long) statsSuccess.getMean());
        // Standard Deviation (ms)
        row.getCell(columnCount++).setCellValue((long) statsSuccess.getStandardDeviation());
    }

    // Auto-size the columns
    for (int i = 0; i < 10; i++) {
        sheet.autoSizeColumn(i);
    }
    sheet.setColumnWidth(1, 5120);

    // Printing
    PrintSetup ps = sheet.getPrintSetup();
    sheet.setAutobreaks(true);
    ps.setFitWidth((short) 1);
    ps.setLandscape(true);

    // Header and footer
    sheet.getHeader().setCenter(title);
}

From source file:org.alfresco.bm.report.XLSXReporter.java

License:Open Source License

private void createPropertiesSheet(XSSFWorkbook workbook) throws IOException, NotFoundException {
    DBObject testRunObj;//from  www. jav a2  s  .c  o  m
    try {
        testRunObj = services.getTestDAO().getTestRun(test, run, true);
    } catch (ObjectNotFoundException e) {
        logger.error("Test run not found!", e);
        return;
    }

    // Ensure we don't leak passwords
    testRunObj = AbstractRestResource.maskValues(testRunObj);

    BasicDBList propertiesList = (BasicDBList) testRunObj.get(FIELD_PROPERTIES);
    if (propertiesList == null) {
        logger.error("Properties not found!");
        return;
    }
    // Order the properties, nicely
    TreeMap<String, DBObject> properties = new TreeMap<String, DBObject>();
    for (Object propertyObj : propertiesList) {
        DBObject property = (DBObject) propertyObj;
        String key = (String) property.get(FIELD_NAME);
        properties.put(key, property);
    }

    XSSFSheet sheet = workbook.createSheet("Properties");

    // Create the fonts we need
    Font fontBold = workbook.createFont();
    fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD);

    // Create the styles we need
    XSSFCellStyle propertyStyle = sheet.getWorkbook().createCellStyle();
    propertyStyle.setAlignment(HorizontalAlignment.RIGHT);
    propertyStyle.setWrapText(true);
    XSSFCellStyle headerStyle = sheet.getWorkbook().createCellStyle();
    headerStyle.setAlignment(HorizontalAlignment.RIGHT);
    headerStyle.setFont(fontBold);

    XSSFRow row = null;
    int rowCount = 0;
    XSSFCell cell = null;
    int cellCount = 0;
    row = sheet.createRow(rowCount++);
    cell = row.createCell(cellCount++);
    {
        cell.setCellValue("Property");
        cell.setCellStyle(headerStyle);
    }
    cell = row.createCell(cellCount++);
    {
        cell.setCellValue("Value");
        cell.setCellStyle(headerStyle);
    }
    cell = row.createCell(cellCount++);
    {
        cell.setCellValue("Origin");
        cell.setCellStyle(headerStyle);
    }
    cellCount = 0;

    // Iterate all the properties for the test run
    for (Map.Entry<String, DBObject> entry : properties.entrySet()) {
        DBObject property = entry.getValue();
        String key = (String) property.get(FIELD_NAME);
        String value = (String) property.get(FIELD_VALUE);
        String origin = (String) property.get(FIELD_ORIGIN);

        row = sheet.createRow(rowCount++);
        cell = row.createCell(cellCount++);
        {
            cell.setCellValue(key);
            cell.setCellStyle(propertyStyle);
        }
        cell = row.createCell(cellCount++);
        {
            cell.setCellValue(value);
            cell.setCellStyle(propertyStyle);
        }
        cell = row.createCell(cellCount++);
        {
            cell.setCellValue(origin);
            cell.setCellStyle(propertyStyle);
        }
        // Back to first column
        cellCount = 0;
    }

    // Size the columns
    sheet.autoSizeColumn(0);
    sheet.setColumnWidth(1, 15360);
    sheet.autoSizeColumn(2);

    // Printing
    PrintSetup ps = sheet.getPrintSetup();
    sheet.setAutobreaks(true);
    ps.setFitWidth((short) 1);
    ps.setLandscape(true);

    // Header and footer
    sheet.getHeader().setCenter(title);
}

From source file:org.bbreak.excella.reports.util.ReportsUtil.java

License:Open Source License

/**
 * fromIdx??toIdx?????/*from  w  w  w . j a va 2  s.  c o m*/
 * @param workbook fromIdx?toIdx??workbook
 * @param fromIdx ?
 * @param sheet 
 */
public static void copyPrintSetup(Workbook workbook, int fromIdx, Sheet toSheet) {
    Sheet fromSheet = workbook.getSheetAt(fromIdx);
    // ?
    PrintSetup fromPrintSetup = fromSheet.getPrintSetup();
    PrintSetup printSetup = toSheet.getPrintSetup();
    printSetup.setCopies(fromPrintSetup.getCopies());
    printSetup.setDraft(fromPrintSetup.getDraft());
    printSetup.setFitHeight(fromPrintSetup.getFitHeight());
    printSetup.setFitWidth(fromPrintSetup.getFitWidth());
    printSetup.setFooterMargin(fromPrintSetup.getFooterMargin());
    printSetup.setHeaderMargin(fromPrintSetup.getHeaderMargin());
    printSetup.setHResolution(fromPrintSetup.getHResolution());
    printSetup.setLandscape(fromPrintSetup.getLandscape());
    printSetup.setLeftToRight(fromPrintSetup.getLeftToRight());
    printSetup.setNoColor(fromPrintSetup.getNoColor());
    printSetup.setNoOrientation(fromPrintSetup.getNoOrientation());
    printSetup.setPageStart(fromPrintSetup.getPageStart());
    printSetup.setPaperSize(fromPrintSetup.getPaperSize());
    printSetup.setScale(fromPrintSetup.getScale());
    printSetup.setUsePage(fromPrintSetup.getUsePage());
    printSetup.setValidSettings(fromPrintSetup.getValidSettings());
    printSetup.setVResolution(fromPrintSetup.getVResolution());
    // ?
    String printArea = workbook.getPrintArea(fromIdx);
    if (printArea != null) {
        if (printArea.contains("!")) {
            printArea = printArea.substring(printArea.indexOf("!") + 1);
        }
        int toIdx = workbook.getSheetIndex(toSheet);
        workbook.setPrintArea(toIdx, printArea);
    }
    // ?
    toSheet.setRepeatingColumns(fromSheet.getRepeatingColumns());
    toSheet.setRepeatingRows(fromSheet.getRepeatingRows());
}

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;//from ww  w .  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(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 ww . ja  va  2s  .  c  o 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.dashbuilder.dataset.service.DataSetExportServicesImpl.java

License:Apache License

SXSSFWorkbook dataSetToWorkbook(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!");
    }/*from w w w .j  a  va  2 s .  c  o m*/
    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);
    SXSSFSheet sh = wb.createSheet("Sheet 1");

    // General setup
    sh.setDisplayGridlines(true);
    sh.setPrintGridlines(false);
    sh.setFitToPage(true);
    sh.setHorizontallyCenter(true);
    sh.trackAllColumnsForAutoSizing();
    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(CellType.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(CellType.NUMERIC);
                cell.setCellStyle(styles.get("decimal_number_cell"));
                cell.setCellValue(((Number) value).doubleValue());
            } else if (value instanceof Date) {
                cell.setCellType(CellType.STRING);
                cell.setCellStyle(styles.get("date_cell"));
                cell.setCellValue((Date) value);
            } else if (value instanceof Interval) {
                cell.setCellType(CellType.STRING);
                cell.setCellStyle(styles.get(TEXT_CELL));
                cell.setCellValue(((Interval) value).getName());
            } else {
                cell.setCellType(CellType.STRING);
                cell.setCellStyle(styles.get(TEXT_CELL));
                String val = value == null ? "" : value.toString();
                cell.setCellValue(val);
            }
        }
    }

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

From source file:org.dkpro.lab.reporting.FlexTable.java

License:Apache License

public StreamWriter getExcelWriter() {
    return new StreamWriter() {
        @Override//from w w w  . j a  v  a2s. c  o  m
        public void write(OutputStream aStream) throws Exception {
            String[] colIds = FlexTable.this.compact ? getCompactColumnIds(false) : getColumnIds();

            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("Summary");

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

            // Header row
            {
                Row row = sheet.createRow(0);
                Cell rowIdCell = row.createCell(0);
                rowIdCell.setCellValue("ID");

                int colNum = 1;
                for (String colId : colIds) {
                    Cell cell = row.createCell(colNum);
                    cell.setCellValue(colId);
                    colNum++;
                }
            }

            // Body rows
            {
                int rowNum = 1;
                for (String rowId : getRowIds()) {
                    Row row = sheet.createRow(rowNum);
                    Cell rowIdCell = row.createCell(0);
                    rowIdCell.setCellValue(rowId);

                    int colNum = 1;
                    for (String colId : colIds) {
                        Cell cell = row.createCell(colNum);
                        String value = getValueAsString(rowId, colId);
                        try {
                            cell.setCellValue(Double.valueOf(value));
                        } catch (NumberFormatException e) {
                            cell.setCellValue(value);
                        }
                        colNum++;
                    }
                    rowNum++;
                }
            }

            wb.write(aStream);
        }
    };
}

From source file:org.h819.commons.file.excel.poi.examples.TimesheetDemo.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/*from www. j  a v  a 2  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("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    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 = "timesheet.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}