Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook XSSFWorkbook

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook XSSFWorkbook

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook XSSFWorkbook.

Prototype

public XSSFWorkbook() 

Source Link

Document

Create a new SpreadsheetML workbook.

Usage

From source file:br.com.algoritmo.compilacao.CompilaXlsx.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/*from   w ww. ja  va 2  s.  c o m*/
    Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();
    data.put(0, new Object[] { 0, "Luiz Carlos Miyadaira Ribeiro Junior", "Base", "0468265522433921",
            "SOFTWARE", null, null, null });
    data.put(1, new Object[] { 1, "Sergio Antnio Andrade de Freitas", "Destino 1", "0395549254894676",
            "SOFTWARE", null, null, null });
    data.put(2, new Object[] { 2, "Andre Luiz Aquere de Cerqueira e Souza", "Destino 2", "8424412648258970",
            "CIVIL", null, null, null });
    data.put(3, new Object[] { 3, "Edson Mintsu Hung Destino", "Destino 3", "6753551743147880", "ELETRNICA",
            null, null, null });
    data.put(4, new Object[] { 4, "Edgard Costa Oliveira", "Destino 4", "1196380808351110", "SOFTWARE", null,
            null, null });
    data.put(5, new Object[] { 5, "Edson Alves da Costa Jnior", "Destino 5", "2105379147123450", "SOFTWARE",
            null, null, null });
    data.put(6, new Object[] { 6, "Andr Barros de Sales", "Destino 6", "7610669796869660", "SOFTWARE", null,
            null, null });
    data.put(7, new Object[] { 7, "Giovanni Almeida dos Santos", "Destino 7", "0580891429319047", "SOFTWARE",
            null, null, null });
    data.put(8, new Object[] { 8, "Cristiane Soares Ramos", "Destino 8", "9950213660160160", "SOFTWARE", null,
            null, null });
    data.put(9, new Object[] { 9, "Fabricio Ataides Braz", "Destino 9", "1700216932505000", "SOFTWARE", null,
            null, null });
    data.put(10, new Object[] { 10, "Alexandre Srgio de Arajo Bezerra", "Destino 10", "0255998976169051",
            "MEDICINA", null, null, null });
    data.put(11, new Object[] { 11, "Eduardo Stockler Tognetti", "Destino 11", "2443108673822680", "ELTRICA",
            null, null, null });
    data.put(12, new Object[] { 12, "Jan Mendona Correa", "Destino 12", "7844006017790570",
            "CINCIA DA COMPUTAO", null, null, null });
    data.put(13, new Object[] { 13, "Rejane Maria da Costa Figueiredo", "Destino 13", "2187680174312042",
            "SOFTWARE", null, null, null });
    data.put(14, new Object[] { 14, "Augusto Csar de Mendona Brasil", "Destino 14", "0571960641751286",
            "ENERGIA", null, null, null });
    data.put(15, new Object[] { 15, "Fbio Macdo Mendes", "Destino 15", "8075435338067780", "F?SICA", null,
            null, null });

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

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

    Sheet aba1 = wb.createSheet("Percentual de similaridade 1");
    PrintSetup printSetup = aba1.getPrintSetup();
    printSetup.setLandscape(true);
    aba1.setFitToPage(true);
    aba1.setHorizontallyCenter(true);

    Sheet aba2 = wb.createSheet("Percentual de similaridade 2");
    PrintSetup printSetup2 = aba2.getPrintSetup();
    printSetup2.setLandscape(true);
    aba1.setFitToPage(true);
    aba1.setHorizontallyCenter(true);

    //title row
    Row titleRow = aba1.createRow(0);
    titleRow.setHeightInPoints(15);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(
            "Resultado da aplicao do algoritmo de clculo do percentual de similaridade entre os indivduos");
    titleCell.setCellStyle(styles.get("title"));
    aba1.addMergedRegion(CellRangeAddress.valueOf("$A$1:$H$1"));

    //header row
    Row headerRow = aba1.createRow(1);
    headerRow.setHeightInPoints(15);
    Cell headerCell;
    for (int i = 1; i <= titles.length; i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(titles[i - 1]);
        headerCell.setCellStyle(styles.get("header"));
    }

    Row headerBase = aba1.createRow(2);
    headerBase.setHeightInPoints(15);
    Cell headerCellBase;
    for (int i = 1; i <= base.length; i++) {
        headerCellBase = headerBase.createCell(i);
        headerCellBase.setCellValue(base[i - 1]);
        headerCellBase.setCellStyle(styles.get("header1"));
    }

    Row headerDestino = aba1.createRow(4);
    headerDestino.setHeightInPoints(15);
    Cell headerCellDestino;
    for (int i = 1; i <= destino.length; i++) {
        headerCellDestino = headerDestino.createCell(i);
        headerCellDestino.setCellValue(destino[i - 1]);
        headerCellDestino.setCellStyle(styles.get("header1"));
    }

    /*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"));
     }
        }
    }
            
    rownum = 3;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles1.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"));
     }
        }
    }
    */
    //set sample data
    //Iterate over data and write to sheet
    Set<Integer> keyset = data.keySet();
    int rownum = 0;
    for (Integer key : keyset) {
        Row row = aba1.createRow(3 + rownum++);
        Object[] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
        }
        if (row.getRowNum() == 3) {
            rownum++;
        }
    }
    //finally set column widths, the width is measured in units of 1/256th of a character width
    aba1.setColumnWidth(0, 2 * 256); //2 characters wide
    aba1.setColumnWidth(1, 26 * 256); //26 characters wide
    aba1.setColumnWidth(2, 20 * 256); //20 characters wide
    aba1.setColumnWidth(3, 18 * 256); //18 characters wide
    aba1.setColumnWidth(4, 20 * 256); //20 characters wide
    for (int i = 5; i < 9; i++) {
        aba1.setColumnWidth(i, 15 * 256); //6 characters wide
    }

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

From source file:br.com.jinsync.controller.ExportExcelBook.java

License:Open Source License

@Override
protected Object doInBackground() throws Exception {

    final String dir = System.getProperty("user.dir") + "\\layouts";

    File arqProp = new File(dir);
    if (!arqProp.exists()) {
        arqProp.mkdirs();/*from  ww w.  j av a2  s.c om*/
    }

    String nameFile = this.nameFile;

    int lin = 0;
    int col = 0;
    int pos = 0;
    int posFim = 0;

    pos = nameFile.lastIndexOf("(");
    if (pos > 0) {
        posFim = nameFile.lastIndexOf(")");
        nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_layout" + ".xlsx";
    } else {
        pos = nameFile.lastIndexOf("\\");
        if (pos > 0) {
            posFim = nameFile.lastIndexOf(".");
            if (posFim > 0) {
                nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_layout" + ".xlsx";
            } else {
                nameFile = dir + nameFile.substring(pos) + "_layout" + ".xlsx";
            }
        }
    }

    FileOutputStream out;

    try {
        out = new FileOutputStream(nameFile);
        TableModel model = tableName.getModel();

        XSSFWorkbook wb = new XSSFWorkbook(); // Criando area de trabalho
        // para o excel
        XSSFSheet s = wb.createSheet(); // criando uma nova sheet

        XSSFFont f = wb.createFont();
        XSSFFont f2 = wb.createFont();

        XSSFCellStyle cs = wb.createCellStyle();
        XSSFCellStyle cs2 = wb.createCellStyle();
        XSSFCellStyle cs3 = wb.createCellStyle();
        XSSFCellStyle cs4 = wb.createCellStyle();

        f.setFontHeightInPoints((short) 8);
        f2.setFontHeightInPoints((short) 8);

        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        f.setFontName("Courier New");
        f2.setFontName("Courier New");

        XSSFRow r = null; // Criando uma referencia para Linha
        XSSFCell c = null; // Referencia para Celula

        cs.setFont(f);
        cs2.setFont(f2);
        cs3.setFont(f2);
        cs4.setFont(f);

        cs2.setAlignment(CellStyle.ALIGN_LEFT);
        cs3.setAlignment(CellStyle.ALIGN_RIGHT);
        cs4.setAlignment(CellStyle.ALIGN_RIGHT);

        r = s.createRow(lin);
        for (int i = 1; i < model.getColumnCount(); i++) {
            c = r.createCell(col);
            c.setCellStyle(cs);
            c.setCellValue(model.getColumnName(i));
            col = col + 1;
        }

        col = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            lin = lin + 1;
            r = s.createRow(lin);
            col = 0;
            for (int j = 1; j < model.getColumnCount(); j++) {
                String valor = model.getValueAt(i, j).toString();
                if (valor == null) {
                    valor = "";
                }

                c = r.createCell(col);
                c.setCellStyle(cs2);

                if (valor.matches("-?\\d+(\\.\\d+)?")) {
                    c.setCellValue(Double.parseDouble(valor));
                    c.setCellType(Cell.CELL_TYPE_NUMERIC);
                    c.setCellStyle(cs4);
                } else {
                    c.setCellValue(valor);
                }
                col = col + 1;
            }
        }

        for (int i = 0; i <= model.getColumnCount(); i++) {
            s.autoSizeColumn(i);
        }

        wb.write(out);
        wb.close();
        out.close();

        Desktop desktop = Desktop.getDesktop();
        desktop.open(new File(nameFile));

    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    }

    return null;

}

From source file:br.com.jinsync.controller.ExportExcelFile.java

License:Open Source License

@Override
protected Object doInBackground() throws Exception {

    int valuePgsBar = 0;
    int qtdTotLin = 0;

    final String dir = System.getProperty("user.dir") + "\\file";

    File arqProp = new File(dir);
    if (!arqProp.exists()) {
        arqProp.mkdirs();/* www.j a  v a 2 s  . c o m*/
    }

    String nameFile = name;

    int lin = 0;
    int col = 0;
    int pos = 0;
    int posEnd = 0;

    pos = nameFile.lastIndexOf("(");
    if (pos > 0) {
        posEnd = nameFile.lastIndexOf(")");
        nameFile = dir + "\\" + nameFile.substring(pos + 1, posEnd) + "_file" + ".xlsx";
    } else {
        pos = nameFile.lastIndexOf("\\");
        if (pos > 0) {
            posEnd = nameFile.lastIndexOf(".");
            if (posEnd > 0) {
                nameFile = dir + "\\" + nameFile.substring(pos + 1, posEnd) + "_file" + ".xlsx";
            } else {
                nameFile = dir + nameFile.substring(pos) + "_file" + ".xlsx";
            }
        }
    }

    FileOutputStream out;

    try {
        out = new FileOutputStream(nameFile);
        TableModel model = tableName.getModel();

        XSSFWorkbook wb = new XSSFWorkbook(); // Criando area de trabalho
        // para o excel
        XSSFSheet s = wb.createSheet(); // criando uma nova sheet

        XSSFFont f = wb.createFont();
        XSSFFont f2 = wb.createFont();

        XSSFCellStyle cs = wb.createCellStyle();
        XSSFCellStyle cs2 = wb.createCellStyle();
        XSSFCellStyle cs3 = wb.createCellStyle();
        XSSFCellStyle cs4 = wb.createCellStyle();

        f.setFontHeightInPoints((short) 8);
        f2.setFontHeightInPoints((short) 8);

        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        f.setFontName("Courier New");
        f2.setFontName("Courier New");

        XSSFRow r = null; // Criando uma referencia para Linha
        XSSFCell c = null; // Referencia para Celula

        cs.setFont(f);
        cs2.setFont(f2);
        cs3.setFont(f2);
        cs4.setFont(f2);

        cs2.setAlignment(CellStyle.ALIGN_LEFT);
        cs3.setAlignment(CellStyle.ALIGN_RIGHT);
        cs4.setAlignment(CellStyle.ALIGN_RIGHT);

        r = s.createRow(lin);
        for (int i = 1; i < model.getColumnCount(); i++) {
            c = r.createCell(col);
            c.setCellStyle(cs);
            c.setCellValue(model.getColumnName(i));
            col = col + 1;
        }

        col = 0;
        qtdTotLin = model.getRowCount() - 1;

        if (qtdTotLin == 0) {
            qtdTotLin = 1;
        }

        for (int i = 0; i < model.getRowCount(); i++) {
            valuePgsBar = (i * 100) / qtdTotLin;
            lin = lin + 1;
            r = s.createRow(lin);
            col = 0;
            for (int j = 1; j < model.getColumnCount(); j++) {
                String valor = model.getValueAt(i, j).toString();
                if (valor == null) {
                    valor = "";
                }

                c = r.createCell(col);
                c.setCellStyle(cs2);

                valor = valor.trim();
                if (valor.matches("-?\\d+(\\.\\d+)?")) {
                    c.setCellValue(Double.parseDouble(valor));
                    c.setCellType(Cell.CELL_TYPE_NUMERIC);
                    c.setCellStyle(cs4);
                } else {
                    c.setCellValue(valor);
                }
                col = col + 1;
                setProgress(valuePgsBar);
            }
        }

        for (int i = 0; i <= model.getColumnCount(); i++) {
            s.autoSizeColumn(i);
        }

        wb.write(out);
        wb.close();
        out.close();

        Desktop desktop = Desktop.getDesktop();
        desktop.open(new File(nameFile));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        e.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:br.com.jinsync.controller.ExportExcelString.java

License:Open Source License

@Override
protected Object doInBackground() throws Exception {

    final String dir = System.getProperty("user.dir") + "\\string";

    File arqProp = new File(dir);
    if (!arqProp.exists()) {
        arqProp.mkdirs();//from   www .  jav  a2  s .co  m
    }

    String nameFile = this.nameFile;

    int lin = 0;
    int col = 0;
    int pos = 0;
    int posFim = 0;
    int valDec = 0;

    pos = nameFile.lastIndexOf("(");
    if (pos > 0) {
        posFim = nameFile.lastIndexOf(")");
        nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_string" + ".xlsx";
    } else {
        pos = nameFile.lastIndexOf("\\");
        if (pos > 0) {
            posFim = nameFile.lastIndexOf(".");
            if (posFim > 0) {
                nameFile = dir + "\\" + nameFile.substring(pos + 1, posFim) + "_string" + ".xlsx";
            } else {
                nameFile = dir + nameFile.substring(pos) + "_string" + ".xlsx";
            }
        }
    }

    FileOutputStream out;

    try {
        out = new FileOutputStream(nameFile);
        TableModel model = tableName.getModel();

        XSSFWorkbook wb = new XSSFWorkbook(); // Criando area de trabalho
        // para o excel
        XSSFSheet s = wb.createSheet(); // criando uma nova sheet

        XSSFFont f = wb.createFont();
        XSSFFont f2 = wb.createFont();

        XSSFCellStyle cs = wb.createCellStyle();
        XSSFCellStyle cs2 = wb.createCellStyle();
        XSSFCellStyle cs3 = wb.createCellStyle();
        XSSFCellStyle cs4 = wb.createCellStyle();

        f.setFontHeightInPoints((short) 8);
        f2.setFontHeightInPoints((short) 8);

        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        f.setFontName("Courier New");
        f2.setFontName("Courier New");

        XSSFRow r = null; // Criando uma referencia para Linha
        XSSFCell c = null; // Referencia para Celula

        cs.setFont(f);
        cs2.setFont(f2);
        cs3.setFont(f2);
        cs4.setFont(f);

        cs2.setAlignment(CellStyle.ALIGN_LEFT);
        cs3.setAlignment(CellStyle.ALIGN_RIGHT);
        cs4.setAlignment(CellStyle.ALIGN_RIGHT);

        r = s.createRow(lin);

        r = s.createRow(0); // Criando a primeira linha na LINHA zero, que
        // seria o nmero 1
        c = r.createCell(0); // Criando a celula na posicao ZERO, que seria
                             // A, com referencia na linha zero acima =
                             // A1
        c.setCellStyle(cs);
        c.setCellValue(Language.stringFieldName);

        c = r.createCell(1);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringType);

        c = r.createCell(2);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringLength);

        c = r.createCell(3);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringDecimal);

        c = r.createCell(4);
        c.setCellStyle(cs);
        c.setCellValue(Language.stringTotal);

        c = r.createCell(5);
        c.setCellStyle(cs4);
        c.setCellValue(Language.stringContent);

        col = 0;
        lin = lin + 1;
        for (int i = 0; i < model.getColumnCount(); i++) {

            r = s.createRow(lin);
            c = r.createCell(col);
            c.setCellStyle(cs2);
            c.setCellValue(model.getColumnName(i));

            col = col + 1;

            c = r.createCell(col);
            c.setCellStyle(cs2);
            c.setCellValue(tipoConteudo.get(i));

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);
            if (tamanhoConteudo.get(i).matches("-?\\d+(\\.\\d+)?")) {
                c.setCellValue(Double.parseDouble(tamanhoConteudo.get(i)));
                c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellStyle(cs3);
            } else {
                c.setCellValue(tamanhoConteudo.get(i));
            }

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);
            if (decimalConteudo.get(i).matches("-?\\d+(\\.\\d+)?")) {
                c.setCellValue(Integer.parseInt(decimalConteudo.get(i)));
                valDec = Integer.parseInt(decimalConteudo.get(i));
                c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellStyle(cs3);
            } else {
                c.setCellValue(decimalConteudo.get(i));
                valDec = 0;
            }

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);
            c.setCellValue(totalConteudo.get(i));

            col = col + 1;
            c = r.createCell(col);
            c.setCellStyle(cs2);

            String valor = model.getValueAt(0, i).toString().trim();
            if (valor == null) {
                valor = "";
            }

            if (valor.matches("-?\\d+(\\.\\d+)?")) {

                if (Double.parseDouble(valor) > 0 && valDec > 0) {
                    double val2 = Double.parseDouble(valor) / (Math.pow(10, valDec));
                    NumberFormat format = NumberFormat.getInstance();
                    format.setMinimumFractionDigits(2);
                    format.setMaximumFractionDigits(valDec);
                    c.setCellValue(format.format(val2).toString());

                } else {
                    c.setCellValue(Double.parseDouble(valor));
                }

                // c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellStyle(cs3);
            } else {
                c.setCellValue(valor);
            }

            lin = lin + 1;
            col = 0;
        }

        for (int i = 0; i <= model.getColumnCount(); i++) {
            s.autoSizeColumn(i);
        }

        wb.write(out);
        wb.close();
        out.close();

        Desktop desktop = Desktop.getDesktop();
        desktop.open(new File(nameFile));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        //e.printStackTrace();
    }

    return null;
}

From source file:br.com.objectos.xls.Spreadsheet.java

License:Apache License

public static Spreadsheet newSpreadsheet() {
    Workbook workbook = new XSSFWorkbook();
    return new Spreadsheet(workbook);
}

From source file:br.com.sose.utils.BigGridDemo_temp.java

License:Apache License

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

    // Step 1. Create a template file. Setup sheets and workbook-level objects such as
    // cell styles, number formats, etc.

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Big Grid");

    Map<String, XSSFCellStyle> styles = createStyles(wb);
    //name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml
    String sheetRef = sheet.getPackagePart().getPartName().getName();

    //save the template
    FileOutputStream os = new FileOutputStream("template.xlsx");
    wb.write(os);//  w w  w.  j av a 2 s . co  m
    os.close();

    //Step 2. Generate XML file.
    File tmp = File.createTempFile("sheet", ".xml");
    Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING);
    generate(fw, styles);
    fw.close();

    //Step 3. Substitute the template entry with the generated data
    FileOutputStream out = new FileOutputStream("big-grid.xlsx");
    substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
    out.close();
}

From source file:br.com.techne.gluonsoft.eowexport.builder.ExcelBuilder.java

License:Apache License

/**
 * mtodo cria bytes de documento Excel//from w ww.  j  a va  2 s  .co  m
 * @param titles
 * @param columnIndex
 * @param dataRows
 * @param locale
 * @return
 * @throws Exception
 */
public static byte[] createExcelBytes(String[] titles, String[] columnIndex,
        List<HashMap<String, Object>> dataRows, Locale locale) throws Exception {

    //Workbook wb = new HSSFWorkbook();
    XSSFWorkbook wb = new XSSFWorkbook();
    byte[] outBytes;

    try {
        HashMap<String, CellStyle> styles = createStyles(wb);
        Sheet sheet = wb.createSheet("Tab 1");

        //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 indexColumn = 0; indexColumn < titles.length; indexColumn++) {
            Cell cell = headerRow.createCell(indexColumn);
            cell.setCellValue(titles[indexColumn]);

            if ((titles.length - 1) < indexColumn) {
                cell.setCellValue("");
            } else
                cell.setCellValue(titles[indexColumn]);

            cell.setCellStyle(styles.get("header"));
        }

        //freeze the first row
        sheet.createFreezePane(0, 1);

        Row row;
        Cell cell;
        int rownum = 1;//devido constar titulo, comea do indice 1

        ValueCellUtil vcutil = new ValueCellUtil(locale);

        for (int indexRow = 0; indexRow < dataRows.size(); indexRow++, rownum++) {

            row = sheet.createRow(rownum);
            HashMap<String, Object> dataRow = dataRows.get(indexRow);

            if (dataRow == null)
                continue;

            List<String> keysAttribs = null;

            if (columnIndex.length == 0) {
                keysAttribs = Arrays.asList(dataRow.keySet().toArray(new String[0]));
                Collections.reverse(keysAttribs);
            } else {
                keysAttribs = Arrays.asList(columnIndex);
            }

            int colCt = 0;

            for (String keyAttrib : keysAttribs) {

                cell = row.createCell(colCt);
                String styleName;
                cell.setCellValue(vcutil.parseValue(dataRow.get(keyAttrib)).toString());

                //zebrando tabela
                if (indexRow % 2 == 0) {
                    // even row
                    styleName = "cell_normal_even";
                } else {
                    // odd row
                    styleName = "cell_normal_odd";
                }

                if (indexRow == 0) {
                    //setando auto ajuste
                    sheet.autoSizeColumn(colCt);
                }

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

        sheet.setZoom(75); //75% scale

        // Write the output to a file
        // write for return byte[]
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            wb.write(out);
            outBytes = out.toByteArray();
        } finally {
            out.close();
        }
    } finally {
        wb.close();
    }

    return outBytes;
}

From source file:br.com.tecsinapse.dataio.Table.java

License:LGPL

public Workbook toXSSFWorkBook() {
    return toWorkBook(new XSSFWorkbook());
}

From source file:br.com.tecsinapse.dataio.util.ExporterUtil.java

License:LGPL

private static void writeSxlsx(List<Table> tables, OutputStream outputStream) throws IOException {
    SXSSFWorkbook wb = new SXSSFWorkbook(new XSSFWorkbook(), 1000);
    writeSpreadsheet(wb, tables, outputStream);
}

From source file:br.com.tecsinapse.dataio.util.ExporterUtil.java

License:LGPL

private static void writeXlsx(List<Table> tables, OutputStream outputStream) throws IOException {
    writeSpreadsheet(new XSSFWorkbook(), tables, outputStream);
}