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

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

Introduction

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

Prototype

void setFitHeight(short height);

Source Link

Document

Set the number of pages high to fit the sheet in

Usage

From source file:org.unitime.timetable.export.XLSPrinter.java

License:Apache License

public XLSPrinter(OutputStream output, boolean checkLast) {
    iOutput = output;//from w w w.  j  a v  a 2s .  co m
    iCheckLast = checkLast;
    iWorkbook = new HSSFWorkbook();
    iSheet = iWorkbook.createSheet();
    iSheet.setDisplayGridlines(false);
    iSheet.setPrintGridlines(false);
    iSheet.setFitToPage(true);
    iSheet.setHorizontallyCenter(true);
    PrintSetup printSetup = iSheet.getPrintSetup();
    printSetup.setLandscape(true);
    iSheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);
    iStyles = new HashMap<String, CellStyle>();

    CellStyle style;

    style = iWorkbook.createCellStyle();
    style.setBorderBottom(BorderStyle.THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(HorizontalAlignment.LEFT);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    style.setFont(getFont(true, false, false, Color.BLACK));
    style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    style.setWrapText(true);
    iStyles.put("header", style);

    style = iWorkbook.createCellStyle();
    style.setAlignment(HorizontalAlignment.LEFT);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    style.setFont(getFont(false, false, false, Color.BLACK));
    style.setWrapText(true);
    iStyles.put("plain", style);

    style = iWorkbook.createCellStyle();
    style.setAlignment(HorizontalAlignment.RIGHT);
    style.setVerticalAlignment(VerticalAlignment.TOP);
    style.setFont(getFont(false, false, false, Color.BLACK));
    iStyles.put("number", style);
}

From source file:packtest.FitSheetToOnePage.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet("format sheet");
    PrintSetup ps = sheet.getPrintSetup();

    sheet.setAutobreaks(true);/*from   w  ww  . ja  v a 2s.  c om*/

    ps.setFitHeight((short) 1);
    ps.setFitWidth((short) 1);

    // Create various cells and rows for spreadsheet.

    FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx");
    wb.write(fileOut);
    fileOut.close();

}

From source file:ro.dabuno.office.integration.BusinessPlan.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;//from  w  w  w  .j ava 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("Business Plan");

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    //the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    //columns for 11 weeks starting from 9-Jul
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);

    calendar.setTime(fmt.parse("9-Jul"));
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    //freeze the first row
    sheet.createFreezePane(0, 1);

    Row row;
    Cell cell;
    int rownum = 1;
    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            cell = row.createCell(j);
            String styleName;
            boolean isHeader = i == 0 || data[i - 1] == null;
            switch (j) {
            case 0:
                if (isHeader) {
                    styleName = "cell_b";
                    cell.setCellValue(Double.parseDouble(data[i][j]));
                } else {
                    styleName = "cell_normal";
                    cell.setCellValue(data[i][j]);
                }
                break;
            case 1:
                if (isHeader) {
                    styleName = i == 0 ? "cell_h" : "cell_bb";
                } else {
                    styleName = "cell_indented";
                }
                cell.setCellValue(data[i][j]);
                break;
            case 2:
                styleName = isHeader ? "cell_b" : "cell_normal";
                cell.setCellValue(data[i][j]);
                break;
            case 3:
                styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                cell.setCellValue(Integer.parseInt(data[i][j]));
                break;
            case 4: {
                calendar.setTime(fmt.parse(data[i][j]));
                calendar.set(Calendar.YEAR, year);
                cell.setCellValue(calendar);
                styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                break;
            }
            case 5: {
                int r = rownum + 1;
                String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")";
                cell.setCellFormula(fmla);
                styleName = isHeader ? "cell_bg" : "cell_g";
                break;
            }
            default:
                styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
            }

            cell.setCellStyle(styles.get(styleName));
        }
    }

    //group rows for each phase, row numbers are 0-based
    sheet.groupRow(4, 6);
    sheet.groupRow(9, 13);
    sheet.groupRow(16, 18);

    //set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 256 * 6);
    sheet.setColumnWidth(1, 256 * 33);
    sheet.setColumnWidth(2, 256 * 20);
    sheet.setZoom(75); //75% scale

    // Write the output to a file
    String file = "businessplan.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();

    wb.close();
}

From source file:rpt.GUI.ProgramStrategist.CyclePlans.CompareDialogController.java

public void okButtonClicked() throws IOException {
    // create two new maps, one for currentCycleplan and one for the comparison plan
    Map<String, TableVariant> currentCyclePlan = new HashMap<String, TableVariant>();
    Map<String, TableVariant> oldCyclePlan = new HashMap<String, TableVariant>();
    Map<String, TableVariant> movedVariants = new HashMap<String, TableVariant>();
    Map<String, TableVariant> changedVariants = new HashMap<String, TableVariant>();
    Map<String, Map<String, String>> changedInfo = new HashMap<String, Map<String, String>>();
    Map<String, String> diffValues = new HashMap<String, String>();

    Statement statement;//from   w  ww  . j a v  a2s  .c  om
    try {
        // Set current YYwWW and use to ignore variants that are no longer in production
        Calendar cal = Calendar.getInstance();
        String currentWeek = cal.get(Calendar.YEAR) % 100 + "w" + cal.get(Calendar.WEEK_OF_YEAR);

        // Extract all variants in the current cycleplan and put them in an map
        System.out.println("Extracting current variants");
        statement = RPT.conn.createStatement();
        statement.setQueryTimeout(30);
        String query = "SELECT * FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                + "VariantBelongsToCyclePlan.CyclePlanID= \'" + CyclePlansController.selectedCyclePlan + "\' "
                + "AND VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID " + "AND EndOfProd > '"
                + currentWeek + "'";
        ResultSet rs = statement.executeQuery(query);

        while (rs.next()) {
            TableVariant entry = new TableVariant(rs.getString("Plant"), rs.getString("Platform"),
                    rs.getString("Vehicle"), rs.getString("Propulsion"), rs.getString("Denomination"),
                    rs.getString("Fuel"), rs.getString("EngineFamily"), rs.getString("Generation"),
                    "EngineName not used", rs.getString("EngineCode"), rs.getString("Displacement"),
                    rs.getString("EnginePower"), rs.getString("ElMotorPower"), rs.getString("Torque"),
                    rs.getString("TorqueOverBoost"), rs.getString("GearboxType"), rs.getString("Gears"),
                    rs.getString("Gearbox"), rs.getString("Driveline"), rs.getString("TransmissionCode"),
                    rs.getString("CertGroup"), rs.getString("EmissionClass"), rs.getString("StartOfProd"),
                    rs.getString("EndOfProd"));
            currentCyclePlan.put(entry.getVariantID(), entry);
        }
        //Now extract all variants in the cycleplan to compare with
        System.out.println("Extracting comparison variants");
        query = "SELECT * FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                + "VariantBelongsToCyclePlan.CyclePlanID= \'"
                + cyclePlanSelector.getSelectionModel().getSelectedItem().toString() + "\' "
                + "AND VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID " + "AND EndOfProd > '"
                + currentWeek + "'";
        rs = statement.executeQuery(query);

        while (rs.next()) {
            TableVariant entry = new TableVariant(rs.getString("Plant"), rs.getString("Platform"),
                    rs.getString("Vehicle"), rs.getString("Propulsion"), rs.getString("Denomination"),
                    rs.getString("Fuel"), rs.getString("EngineFamily"), rs.getString("Generation"),
                    "EngineName not used", rs.getString("EngineCode"), rs.getString("Displacement"),
                    rs.getString("EnginePower"), rs.getString("ElMotorPower"), rs.getString("Torque"),
                    rs.getString("TorqueOverBoost"), rs.getString("GearboxType"), rs.getString("Gears"),
                    rs.getString("Gearbox"), rs.getString("Driveline"), rs.getString("TransmissionCode"),
                    rs.getString("CertGroup"), rs.getString("EmissionClass"), rs.getString("StartOfProd"),
                    rs.getString("EndOfProd"));
            oldCyclePlan.put(entry.getVariantID(), entry);
        }

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    //for each variant in current plan, remove from both if it exists in old
    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        if (oldCyclePlan.containsKey(entry.getKey())) {
            entries.remove(); // remove from currentCyclePlan
            oldCyclePlan.remove(entry.getKey());
        }
    }

    // Now need to check if some entries were only moved in time
    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        try {
            statement = RPT.conn.createStatement();
            statement.setQueryTimeout(30);
            //TODO
            //Add all columns except Start of production, as all will be important to find it correctly
            String query = "SELECT VARIANTS.VariantID, VARIANTS.StartOfProd, VARIANTS.EndOfProd FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                    + "VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID AND "
                    + "VariantBelongsToCyclePlan.CyclePlanID= \'"
                    + cyclePlanSelector.getSelectionModel().getSelectedItem().toString() + "\' AND "
                    + "VARIANTS.Plant = \'" + entry.getValue().getPlant() + "\' AND " + "VARIANTS.Platform = \'"
                    + entry.getValue().getPlatform() + "\' AND " + "VARIANTS.Vehicle = \'"
                    + entry.getValue().getVehicle() + "\' AND " + "VARIANTS.Propulsion = \'"
                    + entry.getValue().getPropulsion() + "\' AND " + "VARIANTS.Denomination = \'"
                    + entry.getValue().getDenomination() + "\' AND " + "VARIANTS.Fuel = \'"
                    + entry.getValue().getFuel() + "\' AND " + "VARIANTS.EngineFamily = \'"
                    + entry.getValue().getEngineFamily() + "\' AND " + "VARIANTS.Generation = \'"
                    + entry.getValue().getGeneration() + "\' AND " + "VARIANTS.EngineCode = \'"
                    + entry.getValue().getEngineCode() + "\' AND " + "VARIANTS.Displacement = \'"
                    + entry.getValue().getDisplacement() + "\' AND " + "VARIANTS.EnginePower = \'"
                    + entry.getValue().getEnginePower() + "\' AND " + "VARIANTS.ElMotorPower = \'"
                    + entry.getValue().getElMotorPower() + "\' AND " + "VARIANTS.TorqueOverBoost = \'"
                    + entry.getValue().getTorqueOverBoost() + "\' AND " + "VARIANTS.GearboxType = \'"
                    + entry.getValue().getGearboxType() + "\' AND " + "VARIANTS.Gears = \'"
                    + entry.getValue().getGears() + "\' AND " + "VARIANTS.Gearbox = \'"
                    + entry.getValue().getGearbox() + "\' AND " + "VARIANTS.Driveline = \'"
                    + entry.getValue().getDriveline() + "\' AND " + "VARIANTS.TransmissionCode = \'"
                    + entry.getValue().getTransmissionCode() + "\' AND " + "VARIANTS.CertGroup = \'"
                    + entry.getValue().getCertGroup() + "\' AND " // may remove once
                    + "VARIANTS.EmissionClass = \'" + entry.getValue().getEmissionClass() + "\'";
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                entry.getValue().setOldSOP(rs.getString("StartOfProd"));
                entry.getValue().setOldEOP(rs.getString("EndOfProd"));
                movedVariants.put(entry.getKey(), entry.getValue()); //Save variant to moved map
                entries.remove(); //remove variant from current map
                oldCyclePlan.remove(rs.getString("VariantID")); //remove variant from old map
            }

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    // Now check for variants that have been slightly changed only.
    // Show a dialog window allowing the user to define what a minor change is
    majorChanges = new ArrayList();
    Stage stage;
    Parent root;
    stage = new Stage();
    root = FXMLLoader
            .load(getClass().getResource("/rpt/GUI/ProgramStrategist/CyclePlans/dialogDefineChanged.fxml"));
    stage.setScene(new Scene(root));
    stage.setTitle("Set change definition");
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.showAndWait(); // pause until the user has selected minor changes

    // Now loop through the remaining Added items and check if they are to be moved to "Modified"
    //for (String s : majorChanges) {
    //    System.out.println(s);
    //}
    // Create string for extracting data which has been judged as minor
    //String dataString = ""; // Data which will be used for difference check
    //for (String s : majorChanges) {
    //    dataString = dataString + ", VARIANTS." + s;
    //}
    // Build list of parameters to extract and compare with the new variant
    ArrayList<String> infoArray = new ArrayList();
    String query = "PRAGMA table_info(VARIANTS)"; //Get all column names
    String extractionData = "";
    try {
        statement = RPT.conn.createStatement();
        statement.setQueryTimeout(30);
        ResultSet rsColumns = statement.executeQuery(query);
        //traverser through list of columns and add those not pointed out as MAJOR
        boolean first = true;
        while (rsColumns.next()) {
            if (!(majorChanges.contains(rsColumns.getString("name")))) {
                infoArray.add(rsColumns.getString("name"));
                if (first) {
                    extractionData = extractionData + "VARIANTS." + rsColumns.getString("name");
                    first = false;
                } else {
                    extractionData = extractionData + ", VARIANTS." + rsColumns.getString("name");
                }
            }
        }

    } catch (Exception e) {
        System.err.println("CompareDialogController error when building extraction data: " + e.getMessage());
    }

    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        try {
            statement = RPT.conn.createStatement();
            statement.setQueryTimeout(30);
            query = "SELECT ";
            query = query + extractionData;
            query = query + " FROM VARIANTS, VariantBelongsToCyclePlan WHERE "
                    + "VARIANTS.VariantID = VariantBelongsToCyclePlan.VariantID AND "
                    + "VariantBelongsToCyclePlan.CyclePlanID= \'"
                    + cyclePlanSelector.getSelectionModel().getSelectedItem().toString() + "\'";

            for (String s : majorChanges) {
                query = query + " AND VARIANTS." + s + " = \'" + entry.getValue().getValue(s) + "\'";
            }
            //System.out.println(query);
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                // Found "similar enough"
                changedVariants.put(entry.getKey(), entry.getValue()); //Save variant to moved map
                entries.remove(); //remove variant from current map
                oldCyclePlan.remove(rs.getString("VariantID")); //remove variant from old map

                // now loop through all non major columns and check for difference between variant in new and old cycle plan
                diffValues = new HashMap<String, String>();
                for (String s : infoArray) {
                    if (!rs.getString(s).equals(entry.getValue().getValue(s))) {
                        diffValues.put(s, rs.getString(s));
                    }
                }

                changedInfo.put(entry.getKey(), diffValues); //Add information about differences between new and old variant
            }

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    // Open file selector and let user specify report file
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Information");

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    // print out information about baseline cycle plan
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    Font headerFont = workbook.createFont();
    headerFont.setBold(true);
    CellStyle style = workbook.createCellStyle();
    style.setFont(headerFont);
    cell.setCellStyle(style);
    cell.setCellValue("Cycle plan:");
    cell = row.createCell(1);
    cell.setCellValue(CyclePlansController.selectedCyclePlan);

    // print out information about comaparison cycle plan
    row = sheet.createRow(1);
    cell = row.createCell(0);
    headerFont = workbook.createFont();
    headerFont.setBold(true);
    style.setFont(headerFont);
    cell.setCellStyle(style);
    cell.setCellValue("Compared to:");
    cell = row.createCell(1);
    cell.setCellValue(cyclePlanSelector.getSelectionModel().getSelectedItem().toString());

    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);

    // Write Added variant information
    sheet = workbook.createSheet("Added");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, false);
    int rowNum = 1;
    int amountOfColumns = 0;
    // loop through added
    for (Iterator<Map.Entry<String, TableVariant>> entries = currentCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), null, false, false);

        rowNum++;
    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    // Write Removed variant information
    sheet = workbook.createSheet("Removed");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, false);
    rowNum = 1;
    // loop through removed
    for (Iterator<Map.Entry<String, TableVariant>> entries = oldCyclePlan.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), null, false, false);

        rowNum++;
    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    // Write Changed variant information
    sheet = workbook.createSheet("Changed");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, false);
    rowNum = 1;
    // loop through changed
    for (Iterator<Map.Entry<String, TableVariant>> entries = changedVariants.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), changedInfo, true, false);

        rowNum++;
    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    // Write Moved variant information
    sheet = workbook.createSheet("Moved");
    //freeze the first row
    sheet.createFreezePane(0, 1);
    row = sheet.createRow(0);
    writeHeaders(workbook, row, true);
    rowNum = 1;
    for (Iterator<Map.Entry<String, TableVariant>> entries = movedVariants.entrySet().iterator(); entries
            .hasNext();) {
        Map.Entry<String, TableVariant> entry = entries.next();
        row = sheet.createRow(rowNum);
        amountOfColumns = writeRow(workbook, sheet, row, entry.getValue(), null, false, true);

        rowNum++;

    }
    //autosize all columns
    for (int i = 0; i < amountOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    amountOfColumns = 0;

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save Comparison Result File");

    File selectedFile = fileChooser.showSaveDialog(null);

    if (selectedFile != null) {
        try {
            FileOutputStream out = new FileOutputStream(selectedFile);
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    closeDialog();
}

From source file:sample.poi.CalendarDemo.java

License:Apache License

public static void main(String[] args) throws Exception {

    Calendar calendar = Calendar.getInstance();

    SimpleDateFormat formatFile = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");

    HSSFWorkbook wb = new HSSFWorkbook();

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

    for (int month = 0; month < 12; month++) {
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //create a sheet for each month
        Sheet sheet = wb.createSheet(months[month]);

        //turn off gridlines
        sheet.setDisplayGridlines(false);
        sheet.setPrintGridlines(false);/*  w  w  w.j a  v a 2s .c  o  m*/
        sheet.setFitToPage(true);
        sheet.setHorizontallyCenter(true);
        PrintSetup printSetup = sheet.getPrintSetup();
        printSetup.setLandscape(true);

        //the following three statements are required only for HSSF
        sheet.setAutobreaks(true);
        printSetup.setFitHeight((short) 1);
        printSetup.setFitWidth((short) 1);

        //the header row: centered text in 48pt font
        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(80);
        Cell titleCell = headerRow.createCell(0);
        titleCell.setCellValue(months[month] + " " + "2013");
        titleCell.setCellStyle(styles.get("title"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));

        //header with month titles
        Row monthRow = sheet.createRow(1);
        for (int i = 0; i < days.length; i++) {
            //set column widths, the width is measured in units of 1/256th of a character width
            sheet.setColumnWidth(i * 2, 5 * 256); //the column is 5 characters wide
            sheet.setColumnWidth(i * 2 + 1, 13 * 256); //the column is 13 characters wide
            sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
            Cell monthCell = monthRow.createCell(i * 2);
            monthCell.setCellValue(days[i]);
            monthCell.setCellStyle(styles.get("month"));
        }

        int cnt = 1, day = 1;
        int rownum = 2;
        for (int j = 0; j < 6; j++) {
            Row row = sheet.createRow(rownum++);
            row.setHeightInPoints(100);
            for (int i = 0; i < days.length; i++) {
                Cell dayCell_1 = row.createCell(i * 2);
                Cell dayCell_2 = row.createCell(i * 2 + 1);

                int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
                if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
                    dayCell_1.setCellValue(day);
                    calendar.set(Calendar.DAY_OF_MONTH, ++day);

                    if (i == 0 || i == days.length - 1) {
                        dayCell_1.setCellStyle(styles.get("weekend_left"));
                        dayCell_2.setCellStyle(styles.get("weekend_right"));
                    } else {
                        dayCell_1.setCellStyle(styles.get("workday_left"));
                        dayCell_2.setCellStyle(styles.get("workday_right"));
                    }
                } else {
                    dayCell_1.setCellStyle(styles.get("grey_left"));
                    dayCell_2.setCellStyle(styles.get("grey_right"));
                }
                cnt++;
            }
            if (calendar.get(Calendar.MONTH) > month)
                break;
        }
    }

    // Write the output to a file
    String file = "calendar.xls";

    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}