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

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

Introduction

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

Prototype

void setPaperSize(short size);

Source Link

Document

Set the paper size.

Usage

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {

    wb = new XSSFWorkbook();
    String safeName = WorkbookUtil.createSafeSheetName(filename);
    Sheet sheet = wb.createSheet(safeName);

    cellStyle = wb.createCellStyle();//from w ww  . j  a v  a  2s  . co m
    facetStyle = wb.createCellStyle();
    titleStyle = wb.createCellStyle();
    createCustomFonts();

    int maxColumns = 0;
    StringTokenizer st = new StringTokenizer(tableId, ",");
    while (st.hasMoreElements()) {
        String tableName = (String) st.nextElement();
        UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                tableName);
        if (component == null) {
            throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
        }
        if (!(component instanceof DataTable || component instanceof DataList)) {
            throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                    + "\", exporter must target a PrimeFaces DataTable/DataList.");
        }

        DataList list = null;
        DataTable table = null;
        int cols = 0;
        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { wb });
        }
        if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
            Row titleRow = sheet.createRow(sheet.getLastRowNum());
            int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum();
            Cell cell = titleRow.createCell(cellIndex);
            cell.setCellValue(new XSSFRichTextString(tableTitle));
            Font titleFont = wb.createFont();
            titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
            titleStyle.setFont(titleFont);
            cell.setCellStyle(titleStyle);
            sheet.createRow(sheet.getLastRowNum() + 3);

        }
        if (component instanceof DataList) {
            list = (DataList) component;

            if (list.getHeader() != null) {
                tableFacet(context, sheet, list, "header");
            }
            if (pageOnly) {
                exportPageOnly(context, list, sheet);
            } else {
                exportAll(context, list, sheet);
            }
            cols = list.getRowCount();
        } else {

            table = (DataTable) component;
            int columnsCount = getColumnsCount(table);

            if (table.getHeader() != null && !subTable) {
                tableFacet(context, sheet, table, columnsCount, "header");

            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "header");
            }

            addColumnFacets(table, sheet, ColumnType.HEADER);

            if (pageOnly) {
                exportPageOnly(context, table, sheet);
            } else if (selectionOnly) {
                exportSelectionOnly(context, table, sheet);
            } else {
                exportAll(context, table, sheet, subTable);
            }

            if (table.hasFooterColumn() && !subTable) {
                addColumnFacets(table, sheet, ColumnType.FOOTER);
            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "footer");
            }
            table.setRowIndex(-1);
            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { wb });
            }
            cols = table.getColumnsCount();

            if (maxColumns < cols) {
                maxColumns = cols;
            }
        }
        sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding));
    }

    if (!subTable)
        for (int i = 0; i < maxColumns; i++) {
            sheet.autoSizeColumn((short) i);
        }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);

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

}

From source file:net.algem.planning.export.PlanningExportService.java

License:Open Source License

/**
 * Export to Excel destination file./*from  w  w  w  .  ja va  2s  . c  o m*/
 *
 * @param dayPlan list of day schedules
 * @param destFile destination file
 * @throws IOException
 */
public void exportPlanning(List<DayPlan> dayPlan, File destFile) throws IOException {
    GemLogger.info("Exporting planning to " + destFile);

    Hour defStartTime = new Hour(ConfigUtil.getConf(ConfigKey.START_TIME.getKey()));
    int offset = defStartTime.getHour();
    int totalh = 24 - offset; // total time length in hours

    HSSFWorkbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("Planning");
    if (dayPlan.size() > 0) {
        DateFormat df = new SimpleDateFormat("EEEE dd MMM yyyy");
        Header header = sheet.getHeader();
        String hd = df.format(dayPlan.get(0).getSchedule().get(0).getDate().getDate());
        header.setCenter(HSSFHeader.fontSize((short) 12) + HSSFHeader.startBold() + hd + HSSFHeader.endBold());
    }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(paperSize);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(false);// was true before 2.15.8
    sheet.setMargin(Sheet.TopMargin, 0.75); // 1.905
    sheet.setMargin(Sheet.BottomMargin, 0.4); // 0.4 inch = 1.016 cm
    sheet.setMargin(Sheet.LeftMargin, 0.4);
    sheet.setMargin(Sheet.RightMargin, 0.4);

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

    Row headerRow = sheet.createRow(0);
    for (int i = 0; i < dayPlan.size(); i++) {
        Cell roomCell = headerRow.createCell(i + 1);
        // Set the width (in units of 1/256th of a character width)
        //sheet.setColumnWidth(i + 1, totalh * 256);// max number of characters must not depend of time length
        sheet.setColumnWidth(i + 1, 24 * 256); // cours.titre character varying(32)
        roomCell.setCellValue(dayPlan.get(i).getLabel());
        roomCell.setCellStyle(styles.get("header"));
    }
    int offsetMn = offset * 60;// offset in minutes
    List<Row> rows = new ArrayList<>();
    System.out.println(" offset = " + offset + " totalh = " + totalh);
    for (int t = 0, rowNumber = 1; t < totalh * 60; t += 5, rowNumber++) { // 1 row = 5mn
        Hour hour = new Hour(offsetMn + t);
        Row row = sheet.createRow(rowNumber);
        //row.setHeightInPoints(25);
        row.setHeightInPoints(PrintSetup.A3_PAPERSIZE == paperSize ? 12 : 6);
        // TIME SUBDIVISIONS
        if (t % 15 == 0) {
            Cell cell = row.createCell(0);
            if (t % 30 == 0) {
                cell.setCellValue(hour.toString());//show time
                if (t % 60 == 0) {
                    cell.setCellStyle(styles.get("hour"));
                } else {
                    cell.setCellStyle(styles.get("hour-half"));
                }
            } else {
                cell.setCellStyle(styles.get("hour-quarter"));
            }
        } else { // BETWEEN SUBDIVISION
            Cell cell = row.createCell(0);
            if ("23:55".equals(hour.toString())) { // last slice
                cell.setCellStyle(styles.get("hour-last"));
            } else {
                cell.setCellStyle(styles.get("hour"));
            }
            if (rowNumber % 3 == 0) { // merge every 3 rows
                sheet.addMergedRegion(new CellRangeAddress(rowNumber - 2, rowNumber, 0, 0));
            }
        }
        rows.add(row);
    }

    Map<java.awt.Color, CellStyle> coursStyleCache = new HashMap<>();

    for (int i = 0; i < dayPlan.size(); i++) {
        DayPlan plan = dayPlan.get(i);
        int col = i + 1;
        for (ScheduleObject event : plan.getSchedule()) {
            // if event starts before default starting time
            if (event.getStart().toMinutes() < offsetMn) {
                event.setStart(new Hour(offset * 60));
            }
            int startRowPos = (event.getStart().toMinutes() - offsetMn) / 5 + 1;
            int endRowPos = (event.getEnd().toMinutes() - offsetMn) / 5;

            Cell courseCell = rows.get(startRowPos - 1).createCell(col);
            courseCell.setCellValue(getLabel(event, workbook));// title text

            CellStyle style = getCourseStyle(workbook, event, coursStyleCache);
            courseCell.setCellStyle(style);
            if (startRowPos != endRowPos) {
                sheet.addMergedRegion(new CellRangeAddress(startRowPos, endRowPos, col, col));
                for (int row = startRowPos; row < endRowPos; row++) {
                    rows.get(row).createCell(col).setCellStyle(style);
                }
            }
        }

    }

    try (FileOutputStream out = new FileOutputStream(destFile)) {
        workbook.write(out);
    }

}

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

License:Open Source License

/**
 * fromIdx??toIdx?????//from  w w w  . j a v a2 s.com
 * @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.pentaho.reporting.engine.classic.core.modules.output.table.xls.helper.ExcelPrintSetupFactory.java

License:Open Source License

/**
 * Performs the page setup and searches a matching page format for the report.
 *
 * @param printSetup/* w ww  .  j  a  va 2  s  . co m*/
 *          the print setup object of the current sheet.
 * @param pageformat
 *          the pageformat defined for the report.
 * @param paperdef
 *          the excel paper size property (may be null).
 * @param paperOrientation
 *          the paper orientation, either "Landscape" or "Portrait"
 */
public static void performPageSetup(final PrintSetup printSetup, final PhysicalPageBox pageformat,
        final String paperdef, final String paperOrientation) {
    short pageCode = ExcelPrintSetupFactory.parsePaperSizeProperty(paperdef);
    if (pageCode == -1) {
        pageCode = ExcelPrintSetupFactory.computePaperSize(pageformat);
    }
    if (pageCode != -1) {
        printSetup.setPaperSize(pageCode);
    }
    if (paperOrientation != null && paperOrientation.equals("auto") == false) {
        printSetup.setLandscape("Landscape".equalsIgnoreCase(paperOrientation));
    } else {
        final boolean landscape = pageformat.getWidth() > pageformat.getHeight();
        printSetup.setLandscape(landscape);
    }
}

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

License:Open Source License

protected void applyOptions(Workbook wb, DataTable table, Sheet sheet, ExporterOptions options) {
    facetStyle = wb.createCellStyle();// ww  w. j a v  a2  s. com
    facetStyle.setAlignment((short) CellStyle.ALIGN_CENTER);
    facetStyle.setVerticalAlignment((short) CellStyle.VERTICAL_CENTER);
    facetStyle.setWrapText(true);
    applyFacetOptions(wb, options, facetStyle);

    cellStyle = wb.createCellStyle();
    cellStyle.setAlignment((short) CellStyle.ALIGN_LEFT);
    applyCellOptions(wb, options, cellStyle);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);
}

From source file:org.primefaces.extensions.component.exporter.ExcelExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {

    wb = new XSSFWorkbook();
    String safeName = WorkbookUtil.createSafeSheetName(filename);
    Sheet sheet = wb.createSheet(safeName);

    cellStyle = wb.createCellStyle();/*from   www .  j ava 2s .co m*/
    facetStyle = wb.createCellStyle();
    titleStyle = wb.createCellStyle();

    facetStyleLeftAlign = wb.createCellStyle();
    facetStyleCenterAlign = wb.createCellStyle();
    facetStyleRightAlign = wb.createCellStyle();
    cellStyleLeftAlign = wb.createCellStyle();
    cellStyleCenterAlign = wb.createCellStyle();
    cellStyleRightAlign = wb.createCellStyle();

    createCustomFonts();

    int maxColumns = 0;
    StringTokenizer st = new StringTokenizer(tableId, ",");
    while (st.hasMoreElements()) {
        String tableName = (String) st.nextElement();
        UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                tableName);
        if (component == null) {
            throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
        }
        if (!(component instanceof DataTable || component instanceof DataList)) {
            throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                    + "\", exporter must target a PrimeFaces DataTable/DataList.");
        }

        DataList list = null;
        DataTable table = null;
        int cols = 0;
        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { wb });
        }
        if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
            Row titleRow = sheet.createRow(sheet.getLastRowNum());
            int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum();
            Cell cell = titleRow.createCell(cellIndex);
            cell.setCellValue(new XSSFRichTextString(tableTitle));
            Font titleFont = wb.createFont();
            titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
            titleStyle.setFont(titleFont);
            cell.setCellStyle(titleStyle);
            sheet.createRow(sheet.getLastRowNum() + 3);

        }
        if (component instanceof DataList) {
            list = (DataList) component;

            if (list.getHeader() != null) {
                tableFacet(context, sheet, list, "header");
            }
            if (pageOnly) {
                exportPageOnly(context, list, sheet);
            } else {
                exportAll(context, list, sheet);
            }
            cols = list.getRowCount();
        } else {

            table = (DataTable) component;
            int columnsCount = getColumnsCount(table);

            if (table.getHeader() != null && !subTable) {
                tableFacet(context, sheet, table, columnsCount, "header");

            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "header");
            }

            addColumnFacets(table, sheet, ColumnType.HEADER);

            if (pageOnly) {
                exportPageOnly(context, table, sheet);
            } else if (selectionOnly) {
                exportSelectionOnly(context, table, sheet);
            } else {
                exportAll(context, table, sheet, subTable);
            }

            if (table.hasFooterColumn() && !subTable) {
                addColumnFacets(table, sheet, ColumnType.FOOTER);
            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "footer");
            }
            table.setRowIndex(-1);
            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { wb });
            }
            cols = table.getColumnsCount();

            if (maxColumns < cols) {
                maxColumns = cols;
            }
        }
        sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding));
    }

    if (!subTable)
        for (int i = 0; i < maxColumns; i++) {
            sheet.autoSizeColumn((short) i);
        }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);

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

}

From source file:org.primefaces.extensions.showcase.util.ExcelCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {

    wb = new XSSFWorkbook();
    String safeName = WorkbookUtil.createSafeSheetName(filename);
    Sheet sheet = wb.createSheet(safeName);

    cellStyle = wb.createCellStyle();/*from  w  w  w.  ja  v  a  2 s.  c o m*/
    facetStyle = wb.createCellStyle();
    titleStyle = wb.createCellStyle();
    createCustomFonts();

    int maxColumns = 0;
    StringTokenizer st = new StringTokenizer(tableId, ",");
    while (st.hasMoreElements()) {
        String tableName = (String) st.nextElement();
        UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                tableName);
        if (component == null) {
            throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
        }
        if (!(component instanceof DataTable || component instanceof DataList)) {
            throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                    + "\", exporter must target a PrimeFaces DataTable/DataList.");
        }

        DataList list = null;
        DataTable table = null;
        int cols = 0;
        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { wb });
        }
        if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
            Row titleRow = sheet.createRow(sheet.getLastRowNum());
            int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum();
            Cell cell = titleRow.createCell(cellIndex);
            cell.setCellValue(new XSSFRichTextString(tableTitle));
            Font titleFont = wb.createFont();
            titleFont.setBold(true);
            titleStyle.setFont(titleFont);
            cell.setCellStyle(titleStyle);
            sheet.createRow(sheet.getLastRowNum() + 3);

        }
        if (component instanceof DataList) {
            list = (DataList) component;

            if (list.getHeader() != null) {
                tableFacet(context, sheet, list, "header");
            }
            if (pageOnly) {
                exportPageOnly(context, list, sheet);
            } else {
                exportAll(context, list, sheet);
            }
            cols = list.getRowCount();
        } else {

            table = (DataTable) component;
            int columnsCount = getColumnsCount(table);

            if (table.getHeader() != null && !subTable) {
                tableFacet(context, sheet, table, columnsCount, "header");

            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "header");
            }

            addColumnFacets(table, sheet, ColumnType.HEADER);

            if (pageOnly) {
                exportPageOnly(context, table, sheet);
            } else if (selectionOnly) {
                exportSelectionOnly(context, table, sheet);
            } else {
                exportAll(context, table, sheet, subTable);
            }

            if (table.hasFooterColumn() && !subTable) {
                addColumnFacets(table, sheet, ColumnType.FOOTER);
            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "footer");
            }
            table.setRowIndex(-1);
            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { wb });
            }
            cols = table.getColumnsCount();

            if (maxColumns < cols) {
                maxColumns = cols;
            }
        }
        sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding));
    }

    if (!subTable) {
        for (int i = 0; i < maxColumns; i++) {
            sheet.autoSizeColumn((short) i);
        }
    }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);

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

}

From source file:org.projectforge.excel.ExportSheet.java

License:Open Source License

public ExportSheet(final ContentProvider contentProvider, final String name, final Sheet poiSheet) {
    this.contentProvider = contentProvider;
    this.name = name;
    this.poiSheet = poiSheet;
    this.rows = new ArrayList<ExportRow>();
    initRowList();/*from  www  .  ja v  a 2 s .  co  m*/
    final PrintSetup printSetup = getPrintSetup();
    printSetup.setPaperSize(ExportConfig.getInstance().getDefaultPaperSizeId());
}

From source file:org.projectforge.export.ExportSheet.java

License:Open Source License

public ExportSheet(final ContentProvider contentProvider, final String name, final Sheet poiSheet) {
    this.contentProvider = contentProvider;
    this.name = name;
    this.poiSheet = poiSheet;
    this.rows = new ArrayList<ExportRow>();
    final int lastRowNum = poiSheet.getLastRowNum();
    if (lastRowNum > 0) {
        // poiSheet does already exists.
        for (int i = poiSheet.getFirstRowNum(); i < poiSheet.getLastRowNum(); i++) {
            final Row poiRow = poiSheet.getRow(i);
            final ExportRow row = new ExportRow(contentProvider, this, poiRow, i);
            rows.add(row);/*w ww.  ja  v a2  s.  c o m*/
        }
    }
    final PrintSetup printSetup = getPrintSetup();
    printSetup.setPaperSize(ConfigXml.getInstance().getDefaultPaperSize());
}

From source file:uk.co.spudsoft.birt.emitters.excel.handlers.PageHandler.java

License:Open Source License

private void setupPageSize(HandlerState state, IPageContent page) {
    PrintSetup printSetup = state.currentSheet.getPrintSetup();
    printSetup.setPaperSize(state.getSmu().getPaperSizeFromString(page.getPageType()));
    if (page.getOrientation() != null) {
        if ("landscape".equals(page.getOrientation())) {
            printSetup.setLandscape(true);
        }/* ww w.j  av  a2s.  co  m*/
    }
}