Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook setPrintArea

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook setPrintArea

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFWorkbook setPrintArea.

Prototype

@Override
public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) 

Source Link

Document

For the Convenience of Java Programmers maintaining pointers.

Usage

From source file:Clavis.Windows.WShedule.java

public void createXLSDocument(String nome, String[][] valores) {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(nome);
    HSSFRow row;/*  w  ww  . j  ava 2  s .  c  o m*/
    HSSFCell cell;
    for (int i = 0; i < valores.length; i++) {
        row = sheet.createRow(i);
        for (int j = 0; j < valores[i].length; j++) {
            cell = row.createCell(j);
            cell.setCellValue(valores[i][j]);
            if (valores[i][j] != null) {
                sheet.setColumnWidth(j, 255 * valores[i][j].length() + 4);
                CellUtil.setAlignment(cell, wb, CellStyle.ALIGN_CENTER);
            }
        }
    }
    wb.setPrintArea(0, 0, valores[0].length, 0, valores.length);
    sheet.getPrintSetup().setPaperSize(XSSFPrintSetup.A4_PAPERSIZE);
    FileOutputStream out;
    String sfile = new File("").getAbsolutePath() + System.getProperty("file.separator") + nome;
    File file = new File(sfile);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(WShedule.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (file.canWrite()) {
        try {
            out = new FileOutputStream(file);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(WShedule.class.getName()).log(Level.SEVERE, null, ex);
            out = null;
        }
        if (out != null) {
            try {
                wb.write(out);
                out.close();
                if (Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().open(file);
                } else {
                    Components.MessagePane mensagem = new Components.MessagePane(this,
                            Components.MessagePane.INFORMACAO, painelcor, lingua.translate("Nota"), 400, 200,
                            lingua.translate("O documento \"doc.xls\" foi criado na pasta raiz do programa")
                                    + ".",
                            new String[] { lingua.translate("Voltar") });
                    mensagem.showMessage();
                }
            } catch (IOException ex) {
                Logger.getLogger(WShedule.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.zhu.action.CarAction.java

public void exportpeople(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from  ww  w  . jav  a 2s. c o  m*/
    CarForm carForm = (CarForm) form;

    // webbookExcel
    HSSFWorkbook wb = new HSSFWorkbook();
    // webbooksheet,Excelsheet
    HSSFSheet sheet = wb.createSheet("?");
    // sheet0,??poiExcel?short
    HSSFRow row = sheet.createRow((int) 0);
    // ? 
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // ?
    HSSFCell cell = row.createCell(0);
    cell.setCellValue("??");
    cell.setCellStyle(style);
    cell = row.createCell(1);
    cell.setCellValue("???");
    cell.setCellStyle(style);
    // ? ??
    OrderService orderService = new OrderService();
    List<Orderinfo> list = orderService.getOrderCarDetail(carForm.getId());
    System.out.println(list.size());
    for (int i = 0; i < list.size(); i++) {
        row = sheet.createRow(i + 1);
        Orderinfo order = (Orderinfo) list.get(i);
        // ?
        row.createCell(0).setCellValue(order.getN1());
        row.createCell(1).setCellValue(order.getI1());
        row = sheet.createRow(i + list.size() + 1);
        row.createCell(0).setCellValue(order.getN2());
        row.createCell(1).setCellValue(order.getI2());
        row = sheet.createRow(i + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN3());
        row.createCell(1).setCellValue(order.getI3());
        row = sheet.createRow(i + list.size() + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN4());
        row.createCell(1).setCellValue(order.getI4());
        row = sheet.createRow(i + list.size() + list.size() + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN5());
        row.createCell(1).setCellValue(order.getI5());
        row = sheet.createRow(i + list.size() + list.size() + list.size() + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN6());
        row.createCell(1).setCellValue(order.getI6());
        row = sheet.createRow(
                i + list.size() + list.size() + list.size() + list.size() + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN7());
        row.createCell(1).setCellValue(order.getI7());
        row = sheet.createRow(i + list.size() + list.size() + list.size() + list.size() + list.size()
                + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN8());
        row.createCell(1).setCellValue(order.getI8());
        row = sheet.createRow(i + list.size() + list.size() + list.size() + list.size() + list.size()
                + list.size() + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN9());
        row.createCell(1).setCellValue(order.getI9());
        row = sheet.createRow(i + list.size() + list.size() + list.size() + list.size() + list.size()
                + list.size() + list.size() + list.size() + list.size() + 1);
        row.createCell(0).setCellValue(order.getN10());
        row.createCell(1).setCellValue(order.getI10());
    }
    // ?
    String filePath = "";
    Date dt = new Date();
    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    String date = df.format(dt).toString();
    filePath = "/Users/Nemo/Documents/carpeople" + date + ".xls";
    File file = new File(filePath);

    try {
        // FileOutputStream fout = new FileOutputStream(
        // "/Users/Nemo/Documents/carpeople.xls");
        // wb.write(fout);
        // fout.close();
        OutputStream out = new FileOutputStream(file);
        wb.write(out);
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    int key = 0;
    int MaxRowNum = 0, MaxCellNum = 0;
    try {
        FileInputStream in = new FileInputStream(filePath);
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook workbook = new HSSFWorkbook(fs);
        FileOutputStream out = new FileOutputStream("/Users/Nemo/Documents/carpeople" + date + ".xls");
        int number = workbook.getNumberOfSheets();
        for (int i = 0; i < number; i++) { // ?sheet
            sheet = workbook.getSheetAt(i); // 14
            System.out.println("" + sheet.getSheetName() + " ? "
                    + (sheet.getLastRowNum() + 1));
            MaxRowNum = 0;
            for (int k = 0; k <= sheet.getLastRowNum(); k++) {
                HSSFRow hRow = sheet.getRow(k);
                // System.out.println((k + 1) + "");
                if (isBlankRow(hRow)) // 
                {
                    int m = 0;
                    for (m = k + 1; m <= sheet.getLastRowNum(); m++) {
                        HSSFRow nhRow = sheet.getRow(m);
                        if (!isBlankRow(nhRow)) {
                            // System.out.println("?" + (m + 1));
                            sheet.shiftRows(m, sheet.getLastRowNum(), k - m);
                            break;
                        }
                    }
                    if (m > sheet.getLastRowNum())
                        break; // ?
                } else { // ?
                    MaxRowNum++;
                    if (MaxCellNum < hRow.getLastCellNum())
                        MaxCellNum = hRow.getLastCellNum();
                }
            }
            workbook.setPrintArea(i, 0, MaxCellNum, 0, MaxRowNum);
            System.out
                    .println("?? " + sheet.getSheetName() + "  " + MaxRowNum);
        }
        workbook.write(out);
        in.close();
        out.close();
    } catch (IOException e) {
        System.out.println(key + " " + e.getMessage() + " ");
        e.printStackTrace();

    }

    System.out.println("??");

}

From source file:Documentos.ClaseAlmacenGeneral.java

public void crearExcel() {
    try {/*from  w ww . j a  v  a 2 s.  co m*/

        // Defino el Libro de Excel
        HSSFWorkbook wb = new HSSFWorkbook();

        // Creo la Hoja en Excel
        Sheet sheet1 = wb.createSheet("Productos");
        Sheet sheet2 = wb.createSheet("hoja2");
        Sheet sheet3 = wb.createSheet("hoja3");

        // quito las lineas del libro para darle un mejor acabado
        //            sheet.setDisplayGridlines(false);
        sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        sheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));

        // creo una nueva fila
        Row trow = sheet1.createRow((short) 0);
        createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                "Productos de Almacn-Repostera AnaIS " + ControllerFechas.getFechaActual());

        // Creo la cabecera de mi listado en Excel
        Row row = sheet1.createRow((short) 2);

        createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cdigo de producto", true,
                true);
        createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Nombre", true, true);
        createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cantidad", true, true);
        createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia", true, true);
        createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia minma", true,
                true);

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/poscakeapp", "root", "");

        try ( // Creamos un Statement para poder hacer peticiones a la bd
                Statement stat = con.createStatement()) {
            ResultSet resultado = stat.executeQuery(
                    "select idProducto, nombre, cantidad,UnidadExistencia,minStock  where tipoProducto=2 from producto");
            while (resultado.next()) {

                //creamos la fila
                Row fila = sheet1.createRow(3 + i);

                String idProducto = String.valueOf(resultado.getString("idProducto"));
                String nombre = String.valueOf(resultado.getString("nombre"));
                String cantidad = String.valueOf(resultado.getInt("cantidad"));
                String UnidadExistencia = String.valueOf(resultado.getInt("UnidadExistencia"));
                String minStock = String.valueOf(resultado.getInt("minStock"));
                // Creo las celdas de mi fila, se puede poner un diseo a la celda
                System.out.println(i + " /// " + idProducto + " - " + nombre + " - " + cantidad + " - "
                        + UnidadExistencia + " - " + minStock);

                creandoCelda(wb, fila, 0, idProducto);
                creandoCelda(wb, fila, 1, nombre);
                creandoCelda(wb, fila, 2, cantidad);
                creandoCelda(wb, fila, 3, UnidadExistencia);
                creandoCelda(wb, fila, 4, minStock);
                i++;
            }
        }
        con.close();

        //            Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que 
        //            la celda se acomode segn su tamao
        Sheet ssheet = wb.getSheetAt(0);
        ssheet.autoSizeColumn(0);
        ssheet.autoSizeColumn(1);
        ssheet.autoSizeColumn(2);
        ssheet.autoSizeColumn(3);
        ssheet.autoSizeColumn(4);
        ssheet.autoSizeColumn(5);
        ssheet.autoSizeColumn(6);
        ssheet.autoSizeColumn(7);

        //Ajustando la hoja de una pagina

        Sheet sheet = wb.createSheet("format sheet");
        PrintSetup ps = sheet.getPrintSetup();
        sheet.setAutobreaks(true);
        ps.setFitHeight((short) 1);
        ps.setFitWidth((short) 1);

        //Area de impresion
        wb.setPrintArea(0, 0, 1, 0, 9);

        String strRuta = System.getProperty("user.dir") + System.getProperty("file.separator") + "reports"
                + System.getProperty("file.separator") + "Almacen" + ControllerFechas.getFechaActual() + ".xls";
        //"C:\\Users\\Tet\\Documents\\GitHub\\gestionProyecto\\4.- Cdigo\\AnaIsRepo" + ControllerFechas.getFechaActual() + ".xls";

        try (FileOutputStream fileOut = new FileOutputStream(strRuta)) {
            wb.write(fileOut);
        }
        JOptionPane.showMessageDialog(null, "Se ha creado!\nSu archivo es:\n" + strRuta);

    } catch (Exception e) {
        e.printStackTrace();
        //JOptionPane.showMessageDialog(null, "El archivo no se ha creado debido a que otro usuario esta haciendo uso de el.\nSe recomienda cerrar el archivo");
    }
}

From source file:Documentos.ClaseAlmacenProducto.java

public void crearExcel() {
    try {/*  www .  j  a  v a  2  s  .  c o  m*/

        // Defino el Libro de Excel
        HSSFWorkbook wb = new HSSFWorkbook();

        // Creo la Hoja en Excel
        Sheet sheet1 = wb.createSheet("Productos");
        Sheet sheet2 = wb.createSheet("hoja2");
        Sheet sheet3 = wb.createSheet("hoja3");

        // quito las lineas del libro para darle un mejor acabado
        //            sheet.setDisplayGridlines(false);
        sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        sheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));

        // creo una nueva fila
        Row trow = sheet1.createRow((short) 0);
        createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                "Productos existentes-Repostera AnaIS " + ControllerFechas.getFechaActual());

        // Creo la cabecera de mi listado en Excel
        Row row = sheet1.createRow((short) 2);

        createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cdigo de producto", true,
                true);
        createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Nombre", true, true);
        createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cantidad", true, true);
        createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Precio de Venta", true,
                true);
        createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Ganancia", true, true);
        createCell(wb, row, 5, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia", true, true);

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/poscakeapp", "root", "");

        try ( // Creamos un Statement para poder hacer peticiones a la bd
                Statement stat = con.createStatement()) {
            ResultSet resultado = stat.executeQuery(
                    "select idproducto,nombre,format(cantidad,0) as cantidad,preciocompra,precioVenta,concat('$ ',format(((precioventa-preciocompra)*cantidad),2)) as ganancia, UnidadExistencia from producto where tipoProducto = 3;");
            while (resultado.next()) {

                //creamos la fila
                Row fila = sheet1.createRow(3 + i);

                String idProducto = String.valueOf(resultado.getString("idProducto"));
                String nombre = String.valueOf(resultado.getString("nombre"));
                String cantidad = String.valueOf(resultado.getInt("cantidad"));
                String precioVenta = String.valueOf(resultado.getString("precioVenta"));
                String ganancia = String.valueOf(resultado.getString("ganancia"));
                String UnidadExistencia = String.valueOf(resultado.getInt("UnidadExistencia"));
                //String Image = String.valueOf(resultado.getBlob("Image"));
                // Creo las celdas de mi fila, se puede poner un diseo a la celda
                System.out.println(i + " /// " + idProducto + " - " + nombre + " - " + cantidad + " - "
                        + precioVenta + " - " + ganancia + " - " + UnidadExistencia);

                creandoCelda(wb, fila, 0, idProducto);
                creandoCelda(wb, fila, 1, nombre);
                creandoCelda(wb, fila, 2, cantidad);
                creandoCelda(wb, fila, 3, precioVenta);
                creandoCelda(wb, fila, 4, ganancia);
                creandoCelda(wb, fila, 5, UnidadExistencia);
                //creandoCelda(wb, fila, 5, Image);
                i++;
            }
        }
        con.close();

        //            Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que 
        //            la celda se acomode segn su tamao
        Sheet ssheet = wb.getSheetAt(0);
        ssheet.autoSizeColumn(0);
        ssheet.autoSizeColumn(1);
        ssheet.autoSizeColumn(2);
        ssheet.autoSizeColumn(3);
        ssheet.autoSizeColumn(4);
        ssheet.autoSizeColumn(5);
        ssheet.autoSizeColumn(6);
        ssheet.autoSizeColumn(7);

        //Ajustando la hoja de una pagina

        Sheet sheet = wb.createSheet("format sheet");
        PrintSetup ps = sheet.getPrintSetup();
        sheet.setAutobreaks(true);
        ps.setFitHeight((short) 1);
        ps.setFitWidth((short) 1);

        //Area de impresion
        wb.setPrintArea(0, 0, 1, 0, 9);

        String strRuta = System.getProperty("user.dir") + System.getProperty("file.separator") + "reports"
                + System.getProperty("file.separator") + "Productos" + ControllerFechas.getFechaActual()
                + ".xls";
        //"C:\\Users\\Tet\\Documents\\GitHub\\gestionProyecto\\4.- Cdigo\\AnaIsRepo" + ControllerFechas.getFechaActual() + ".xls";

        try (FileOutputStream fileOut = new FileOutputStream(strRuta)) {
            wb.write(fileOut);
        }
        JOptionPane.showMessageDialog(null, "Se ha creado!\nSu archivo es:\n" + strRuta);

    } catch (Exception e) {
        e.printStackTrace();
        //JOptionPane.showMessageDialog(null, "El archivo no se ha creado debido a que otro usuario esta haciendo uso de el.\nSe recomienda cerrar el archivo");
    }
}

From source file:Documentos.ClaseAlmacenXLS.java

public void crearExcel() {
    try {//ww w  .  j  a v a  2 s .c o m

        // Defino el Libro de Excel
        HSSFWorkbook wb = new HSSFWorkbook();

        // Creo la Hoja en Excel
        Sheet sheet1 = wb.createSheet("Productos");
        Sheet sheet2 = wb.createSheet("hoja2");
        Sheet sheet3 = wb.createSheet("hoja3");

        // quito las lineas del libro para darle un mejor acabado
        //            sheet.setDisplayGridlines(false);
        sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        sheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));

        // creo una nueva fila
        Row trow = sheet1.createRow((short) 0);
        createTituloCell(wb, trow, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                "Productos de Almacn-Repostera AnaIS " + ControllerFechas.getFechaActual());

        // Creo la cabecera de mi listado en Excel
        Row row = sheet1.createRow((short) 2);

        createCell(wb, row, 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cdigo de producto", true,
                true);
        createCell(wb, row, 1, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Nombre", true, true);
        createCell(wb, row, 2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Cantidad", true, true);
        createCell(wb, row, 3, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia", true, true);
        createCell(wb, row, 4, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER, "Existencia minma", true,
                true);

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/poscakeapp", "root", "");

        try ( // Creamos un Statement para poder hacer peticiones a la bd
                Statement stat = con.createStatement()) {
            ResultSet resultado = stat.executeQuery(
                    "select idProducto, nombre, cantidad,UnidadExistencia,minStock from producto where tipoProducto=2 ");
            while (resultado.next()) {

                //creamos la fila
                Row fila = sheet1.createRow(3 + i);

                String idProducto = String.valueOf(resultado.getString("idProducto"));
                String nombre = String.valueOf(resultado.getString("nombre"));
                String cantidad = String.valueOf(resultado.getInt("cantidad"));
                String UnidadExistencia = String.valueOf(resultado.getInt("UnidadExistencia"));
                String minStock = String.valueOf(resultado.getInt("minStock"));
                // Creo las celdas de mi fila, se puede poner un diseo a la celda
                System.out.println(i + " /// " + idProducto + " - " + nombre + " - " + cantidad + " - "
                        + UnidadExistencia + " - " + minStock);

                creandoCelda(wb, fila, 0, idProducto);
                creandoCelda(wb, fila, 1, nombre);
                creandoCelda(wb, fila, 2, cantidad);
                creandoCelda(wb, fila, 3, UnidadExistencia);
                creandoCelda(wb, fila, 4, minStock);
                i++;
            }
        }
        con.close();

        //            Definimos el tamao de las celdas, podemos definir un tamaa especifico o hacer que 
        //            la celda se acomode segn su tamao
        Sheet ssheet = wb.getSheetAt(0);
        ssheet.autoSizeColumn(0);
        ssheet.autoSizeColumn(1);
        ssheet.autoSizeColumn(2);
        ssheet.autoSizeColumn(3);
        ssheet.autoSizeColumn(4);
        ssheet.autoSizeColumn(5);
        ssheet.autoSizeColumn(6);
        ssheet.autoSizeColumn(7);

        //Ajustando la hoja de una pagina

        Sheet sheet = wb.createSheet("format sheet");
        PrintSetup ps = sheet.getPrintSetup();
        sheet.setAutobreaks(true);
        ps.setFitHeight((short) 1);
        ps.setFitWidth((short) 1);

        //Area de impresion
        wb.setPrintArea(0, 0, 1, 0, 9);

        String strRuta = System.getProperty("user.dir") + System.getProperty("file.separator") + "reports"
                + System.getProperty("file.separator") + "Almacen" + ControllerFechas.getFechaActual() + ".xls";
        //"C:\\Users\\Tet\\Documents\\GitHub\\gestionProyecto\\4.- Cdigo\\AnaIsRepo" + ControllerFechas.getFechaActual() + ".xls";

        try (FileOutputStream fileOut = new FileOutputStream(strRuta)) {
            wb.write(fileOut);
        }
        JOptionPane.showMessageDialog(null, "Se ha creado!\nSu archivo es:\n" + strRuta);

    } catch (Exception e) {
        e.printStackTrace();
        //JOptionPane.showMessageDialog(null, "El archivo no se ha creado debido a que otro usuario esta haciendo uso de el.\nSe recomienda cerrar el archivo");
    }
}

From source file:org.sharegov.cirm.utils.ExcelExportUtil.java

License:Apache License

public void exportData(OutputStream out, Json allData) throws IOException {
    //Set the filename
    Date dt = new Date();
    SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy");
    String filename = fmt.format(dt);

    // Create Excel Workbook and Sheet
    HSSFWorkbook wb = new HSSFWorkbook();
    sheet = wb.createSheet(filename);//from  w w  w  .j a v a2  s .  com
    HSSFHeader header = sheet.getHeader();
    header.setCenter(filename);

    HSSFFont boldFont = wb.createFont();
    boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    HSSFCellStyle boldStyle = wb.createCellStyle();
    boldStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    boldStyle.setFont(boldFont);
    boldStyle.setWrapText(true);

    //Start : populate the spreadsheet
    int rowCounter = 0;
    rowCounter = searchCriteriaRows(allData, boldStyle);
    rowCounter = headerRow(allData, boldStyle, rowCounter);
    int headingsRowSplitter = rowCounter;
    rowCounter = dataRows(allData, rowCounter);
    //end : populate the spreadsheet

    // Freeze Panes on Header Row
    sheet.createFreezePane(0, headingsRowSplitter);
    // Row 1 Repeats on each page
    wb.setRepeatingRowsAndColumns(0, 0, 0, 0, headingsRowSplitter);

    // Set Print Area, Footer
    int colCount = allData.at("metaData").at("columns").asInteger();
    wb.setPrintArea(0, 0, colCount, 0, rowCounter);
    HSSFFooter footer = sheet.getFooter();
    footer.setCenter("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
    // Fit Sheet to 1 page wide but very long
    sheet.setAutobreaks(true);
    HSSFPrintSetup ps = sheet.getPrintSetup();
    ps.setFitWidth((short) 1);
    ps.setFitHeight((short) 9999);
    sheet.setGridsPrinted(true);
    sheet.setHorizontallyCenter(true);
    ps.setPaperSize(HSSFPrintSetup.LETTER_PAPERSIZE);
    if (colCount > 5) {
        ps.setLandscape(true);
    }
    if (colCount > 10) {
        ps.setPaperSize(HSSFPrintSetup.LEGAL_PAPERSIZE);
    }
    if (colCount > 14) {
        ps.setPaperSize(HSSFPrintSetup.EXECUTIVE_PAPERSIZE);
    }
    // Set Margins
    ps.setHeaderMargin((double) .35);
    ps.setFooterMargin((double) .35);
    sheet.setMargin(HSSFSheet.TopMargin, (double) .50);
    sheet.setMargin(HSSFSheet.BottomMargin, (double) .50);
    sheet.setMargin(HSSFSheet.LeftMargin, (double) .50);
    sheet.setMargin(HSSFSheet.RightMargin, (double) .50);

    // Write out the spreadsheet
    wb.write(out);
    out.close();
}