Example usage for org.apache.poi.ss.usermodel Workbook close

List of usage examples for org.apache.poi.ss.usermodel Workbook close

Introduction

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

Prototype

@Override
void close() throws IOException;

Source Link

Document

Close the underlying input resource (File or Stream), from which the Workbook was read.

Usage

From source file:list.java

public List<city> readcityFromExcelFile(String excelFilePath) throws IOException {
    List<city> listcity = new ArrayList<>();
    FileInputStream inputStream = new FileInputStream(new File(excelFilePath));

    Workbook workbook = new XSSFWorkbook(inputStream);
    Sheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> iterator = firstSheet.iterator();

    while (iterator.hasNext()) {
        Row nextRow = iterator.next();//from   w  w  w  . jav a 2  s .c om

        Iterator<Cell> cellIterator = nextRow.cellIterator();
        city acity = new city();

        while (cellIterator.hasNext()) {
            Cell nextCell = cellIterator.next();
            int columnIndex = nextCell.getColumnIndex();

            switch (columnIndex) {
            case 0:
                acity.setCompany(nextCell.getStringCellValue());
                break;
            case 1:
                acity.setFrom(nextCell.getStringCellValue());
                break;
            case 2:

                acity.setTo(nextCell.getStringCellValue());
                break;

            case 3:

                acity.setFare(nextCell.getNumericCellValue());

                break;
            case 4:
                acity.setTime(nextCell.getNumericCellValue());
                break;
            }

        }
        listcity.add(acity);

    }

    workbook.close();
    inputStream.close();

    return listcity;
}

From source file:StateContentTest.java

/**
 * Reads the first sheet of the specified Excel spreadsheet into a Hashtable, 
 * where the value in the first column of each row is the Key and the following columns are added to a String[] of size columns
 * @param filename The name of the file to open including extension.
 * @param rows The number of rows to read.
 * @param columns The number of columns to read.
 * @param rowStart The row to start reading from.
 * @param colStart The column to start reading from.
 * @throws IOException/*from  www  . ja  v  a 2s .  c o  m*/
 */
private void readExcel(String filename, int rows, int columns, int rowStart, int colStart) throws IOException {
    FileInputStream inputStream = new FileInputStream(new File("./data/" + filename));

    Workbook workbook = new XSSFWorkbook(inputStream);
    Sheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> iterator = firstSheet.iterator();
    iterator.next();
    iterator.next();

    for (int i = rowStart; i < rows; i++) {
        Row row = firstSheet.getRow(i);
        String[] copy = new String[columns];
        String stateName = "";
        for (int j = colStart; j < columns - 1; j++) {
            if (j == colStart)
                stateName = row.getCell(j).getStringCellValue();
            else
                copy[j] = row.getCell(j).getStringCellValue().replaceAll("\\u2022", "")
                        .replaceAll("(?m)^[ \t]*\r?\n", "").trim();
        }
        copyMatrix.put(stateName, copy);
    }

    workbook.close();
    inputStream.close();
}

From source file:ApachePOIExcelWrite.java

@Override
public void doInvokeMethod(String MethodName, SiebelPropertySet inputs, SiebelPropertySet outputs)
        throws SiebelBusinessServiceException {
    if (MethodName.equalsIgnoreCase("GenerateExcelDoc")) {
        try {//from ww  w. j  a v  a  2s  . c om
            //
            //IProperties AP = new ApplicationProperties();
            SiebelDataBean conn = ApplicationsConnection.connectSiebelServer();
            //Get excel path
            System.out.println(HelperAP.getInvoiceTemplate());
            inputFile = HelperAP.getInvoiceTemplate();
            //Read Excel document first
            input_document = new FileInputStream(new File(inputFile));
            // Convert it into a POI object
            Workbook my_xlsx_workbook = WorkbookFactory.create(input_document);
            // Read excel sheet that needs to be updated
            Sheet my_worksheet = my_xlsx_workbook.getSheet("Sheet1");
            // Declare a Cell object
            this.order_id = inputs.getProperty("QuoteId");
            this.quote_number = inputs.getProperty("QuoteNum");

            CustomerRecord customerInfo = new CustomerRecord(my_xlsx_workbook, my_worksheet, 3);
            customerInfo.setQuoteId(this.order_id);
            customerInfo.createCellFromList(new QShippment(conn), new ContactKey());
            customerInfo.setStartRow(8);
            customerInfo.createCellFromList(new QAddress(conn), new ContactKey());

            InvoiceExcel parts;

            int startRowAt = 17;
            parts = new InvoiceExcel(my_xlsx_workbook, my_worksheet);

            //
            parts.setStartRow(startRowAt);
            parts.setQuoteId(order_id);
            parts.createCellFromList(new QParts(conn), new ContactKey());
            my_xlsx_workbook.setForceFormulaRecalculation(true);
            input_document.close();
            XGenerator.doCreateBook(my_xlsx_workbook, "weststar_" + this.quote_number.replace(" ", "_"));
            Attachment a = new Attachment(conn, "Quote", "Quote Attachment");
            String filepath = XGenerator.getProperty("filepath");
            String filename = XGenerator.getProperty("filename");

            //Attach the file to siebel
            a.Attach(filepath, filename, Boolean.FALSE, order_id);

            boolean logoff = conn.logoff();
            my_xlsx_workbook.close();
            System.out.println("Done");
            outputs.setProperty("status", "success");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE,
                    "Caught File Not Found Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (IOException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE, "Caught IO Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (InvalidFormatException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE,
                    "Caught Invalid Format Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (EncryptedDocumentException ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE,
                    "Caught Encrypted Document Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        } catch (Exception ex) {
            ex.printStackTrace(new PrintWriter(error_txt));
            MyLogging.log(Level.SEVERE, "Caught Exception: " + ex.getMessage() + error_txt.toString());
            outputs.setProperty("status", "failed");
            outputs.setProperty("error_message", error_txt.toString());
        }
    }
}

From source file:blanco.commons.calc.parser.AbstractBlancoCalcParser.java

License:Open Source License

/**
 * ???//from  ww  w.  ja  va 2s.  c o m
 * 
 * @param inputSource
 *            ???
 * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
 */
public final void parse(final InputSource inputSource) throws IOException, SAXException {

    System.out.println("AbstractBlancoCalcParser#:parse");

    Workbook workbook = null;

    InputStream inStream = null;
    try {
        if (inputSource.getByteStream() != null) {
            // OK??????????
        } else if (inputSource.getSystemId() != null && inputSource.getSystemId().length() > 0) {
            inStream = new FileInputStream(inputSource.getSystemId());
            inputSource.setByteStream(inStream);
        } else {
            throw new IOException("??InputSource???????.");
        }
        workbook = WorkbookFactory.create(inputSource.getByteStream());

        // ????????
        parseWorkbook(workbook);
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("???????.: " + e.toString());
    } catch (InvalidFormatException e) {
        e.printStackTrace();
        throw new IOException("???????.: " + e.toString());
    } finally {
        if (workbook != null) {
            workbook.close();
        }

        // InputSource??????
        // ???? ?????????
        if (inStream != null) {
            inStream.close();
        }
    }
}

From source file:br.sp.telesul.service.ExportServiceImpl.java

@Override
public List<Funcionario> readExcelDocument() {
    try {//from w w w. j av a  2s .c o  m
        List<Funcionario> funcionariosExcel = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        //            FileInputStream fl = new FileInputStream(new File("C:\\Matriz1.xlsx"));
        Workbook wb = new XSSFWorkbook(classLoader.getResourceAsStream("Matriz1.xlsx"));
        Sheet firstSheet = wb.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();

        while (iterator.hasNext()) {
            Row nextRow = iterator.next();
            int row = nextRow.getRowNum();
            //                System.out.println("Row start" + row);
            Iterator<Cell> cellIterator = nextRow.cellIterator();
            Funcionario f = new Funcionario();
            Formacao fm = new Formacao();
            Idioma id = new Idioma();
            int column = 0;
            while (cellIterator.hasNext()) {
                Cell nextCell = cellIterator.next();
                int columnIndex = nextCell.getColumnIndex();
                column = columnIndex;
                //                    System.out.println("Valor" + getCellValue(nextCell));
                //                    System.out.println("Index: " + columnIndex);
                if (row > 0) {
                    switch (columnIndex) {
                    case 1:
                        f.setArea((String) getCellValue(nextCell));
                        break;
                    case 2:
                        Date dt = new Date();
                        if (!getCellValue(nextCell).toString().isEmpty()) {
                            try {
                                dt = DateUtil.getJavaDate((Double) getCellValue(nextCell));
                            } catch (ClassCastException cce) {
                                SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");

                                dt = formatter.parse((String) getCellValue((nextCell)));
                            }
                            ;
                        }

                        f.setDtAdmissao(dt);
                        break;
                    case 3:
                        f.setCargo((String) getCellValue(nextCell));
                        break;
                    case 4:
                        f.setNome((String) getCellValue(nextCell));
                        break;
                    case 5:
                        f.setGestor((String) getCellValue(nextCell));
                        break;
                    case 9:
                        fm.setNivel((String) getCellValue(nextCell));
                        break;
                    case 10:
                        fm.setCurso((String) getCellValue(nextCell));
                        break;
                    case 11:
                        fm.setInstituicaoo((String) getCellValue(nextCell));
                        break;
                    case 12:
                        String typeEnum = (String) getCellValue(nextCell);
                        if (!typeEnum.isEmpty()) {
                            id.setNome(Language.valueOf(typeEnum.trim()));
                        }

                        break;
                    case 13:
                        String typeEnumNivel = (String) getCellValue(nextCell);
                        if (!typeEnumNivel.isEmpty()) {
                            id.setNivel(Nivel.valueOf(typeEnumNivel.trim()));
                        }

                        break;
                    }
                }

            }

            List<Formacao> listFm = new ArrayList<>();
            listFm.add(fm);
            f.setFormacoes(listFm);

            List<Idioma> listId = new ArrayList<>();
            listId.add(id);
            f.setIdiomas(listId);

            if (row > 0) {
                funcionariosExcel.add(f);
            }

        }
        wb.close();
        //            fl.close();
        //            for (Funcionario fc : funcionariosExcel) {
        //                System.out.println(fc.getNome());
        //            }
        return funcionariosExcel;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:ch.bfh.lca._15h.library.export.ExportToExcel.java

/***
 * Generate an Excel file based on a list of results.
 * Use the name of the fields described in the GenericResultRow to label the columns.
 * @param language Language of the label in the Excel file
 * @param sheetTitle Title of the sheet in the Excel file
 * @param tableTitle Title of the table in the Excel file
 * @param rows Arrays of rows to include in the listing
 * @param excelFilePath Path of the outputed file
 * @throws FileNotFoundException//  ww  w . j a va 2s  . c  o m
 * @throws IOException 
 */
public static void exportToExcel(Translation.TRANSLATION_LANGUAGE language, String sheetTitle,
        String tableTitle, GenericResultRow[] rows, String excelFilePath)
        throws FileNotFoundException, IOException {
    //Workbook wb = new HSSFWorkbook(); //xls
    Workbook wb = new SXSSFWorkbook(); //xlsx
    //create new sheet
    Sheet sheet1 = wb.createSheet(sheetTitle);
    Row row;
    Cell cell;
    String translation;

    int rowIndex = 0;

    //add title
    row = sheet1.createRow((short) rowIndex);
    cell = row.createCell(0);
    cell.setCellValue(tableTitle);
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontHeightInPoints((short) 24);
    //font.setFontName("Courier New");
    style.setFont(font);
    cell.setCellStyle(style);

    //add rows
    for (int i = 0; i < rows.length; i++) {
        //if first line, write col names
        if (i == 0) {
            row = sheet1.createRow((short) rowIndex + 2);

            for (int j = 0; j < rows[i].getColNames().length; j++) {
                cell = row.createCell(j);

                //look for translation
                translation = Translation.getForKey(language, rows[i].getColNames()[j]);
                if (translation == null) {
                    translation = rows[i].getColNames()[j]; //if doesn't found a translation for the column take name of col
                }
                cell.setCellValue(translation);
            }
        }

        row = sheet1.createRow((short) (rowIndex + i + 3));

        for (int j = 0; j < rows[i].getColNames().length; j++) {
            cell = row.createCell(j);
            cell.setCellValue(rows[i].getValueAt(j).toString());
        }
    }

    //write to the file
    FileOutputStream fileOut = new FileOutputStream(excelFilePath);
    wb.write(fileOut);
    fileOut.close();

    wb.close();
}

From source file:chronostone.parser.ChronoStoneParser.java

public static void main(String[] args) throws FileNotFoundException, IOException {

    String rutaArchivo = System.getProperty("user.home") + "/ChronoStoneSheet.xls";
    File archivoXLS = new File(rutaArchivo);
    if (archivoXLS.exists() == false) {
        try {//from   w ww.  j a v  a2 s  .  c o m
            archivoXLS.createNewFile();
        } catch (IOException ex) {
            System.err.println("Error on creating XLS");
        }
    }

    Workbook libro = new HSSFWorkbook();
    FileOutputStream archivo = new FileOutputStream(archivoXLS);
    Sheet hoja = libro.createSheet("Chrono Stone Sheet");
    /**
     * Codigo a remover o investigar como hacerlo funcionar de verdad
     */
    int check = check_created(hoja);
    if (check == xls_index) {
        inicializar_celdas(hoja);
    } else {
        xls_index = check + 1;
    }
    String name = "";
    System.out.println("Archivo creado: " + rutaArchivo);
    System.out.println("Introduzca nombre");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    name = br.readLine();
    while (!name.equalsIgnoreCase("exit")) {
        try {

            tenmakun = new Character(name);
            name = name.replace(" ", "_");
            URLConnection connection = null;
            connection = new URL(root + name).openConnection();
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while ((line = bf.readLine()) != null) {
                if (line.contains(ONE_STATS) || line.contains(TWO_STATS) || line.contains(AURA_HTML)) {
                    //Primero los stats
                    List<String> stats = new ArrayList<>();
                    for (int index = 0; index < 13; index++) {
                        stats.add(bf.readLine());
                    }
                    add_stats(stats);
                    //Y ahora a por las habilidades
                    //add_hissatsu(stats);
                } else if (line.contains("<a href=\"/wiki/Category:Midfielders\"")) {
                    tenmakun.setPosition(MF);
                } else if (line.contains("<a href=\"/wiki/Category:Forwards\"")) {
                    tenmakun.setPosition(FW);
                } else if (line.contains("<a href=\"/wiki/Category:Defenders\"")) {
                    tenmakun.setPosition(DF);
                } else if (line.contains("<a href=\"/wiki/Category:Goalkeepers\"")) {
                    tenmakun.setPosition(GK);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println(tenmakun.print_stats());
        add_character_sheet(hoja);
        System.out.println("Personaje aadido al fichero");
        System.out.println("Introduzca nombre");
        name = br.readLine();
    }
    libro.write(archivo);
    archivo.close();
    libro.close();
}

From source file:cl.a2r.wsmicampov2.common.utils.Excel.java

public static void GenerateExcel(String fileUrl, String sheetName, List<Integer> dataList) {

    File archivo = new File(fileUrl);
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet(sheetName);

    int rowNum = 1;
    for (Integer data : dataList) {

        Row row = sheet.createRow(rowNum++);

        row.createCell(0).setCellValue(data);
    }// w  ww .j av  a  2  s.  c  o  m
    try {
        FileOutputStream salida = new FileOutputStream(archivo);
        workbook.write(salida);
        workbook.close();

    } catch (FileNotFoundException ex) {
        AppLog.logInfo(ex.getMessage(), ex);

    } catch (IOException ex) {
        AppLog.logInfo(ex.getMessage(), ex);
    } catch (Exception ex) {
        AppLog.logInfo(ex.getMessage(), ex);

    }

}

From source file:cn.com.zhbook.component.poi.PoiPerformanceTest.java

License:Apache License

public static void main(String[] args) throws IOException {
    if (args.length != 4)
        usage("need four command arguments");

    String type = args[0];/*from  ww  w  .j a v  a2s  .  co m*/
    long timeStarted = System.currentTimeMillis();
    Workbook workBook = createWorkbook(type);
    boolean isHType = workBook instanceof HSSFWorkbook;

    int rows = parseInt(args[1], "Failed to parse rows value as integer");
    int cols = parseInt(args[2], "Failed to parse cols value as integer");
    boolean saveFile = parseInt(args[3], "Failed to parse saveFile value as integer") != 0;

    addContent(workBook, isHType, rows, cols);

    if (saveFile) {
        String fileName = type + "_" + rows + "_" + cols + "." + getFileSuffix(args[0]);
        saveFile(workBook, fileName);
    }
    long timeFinished = System.currentTimeMillis();
    System.out.println("Elapsed " + (timeFinished - timeStarted) / 1000 + " seconds");

    workBook.close();
}

From source file:com.actelion.research.spiritapp.ui.util.POIUtils.java

License:Open Source License

@SuppressWarnings("rawtypes")
public static void exportToExcel(String[][] table, ExportMode exportMode) throws IOException {
    Class[] types = getTypes(table);
    Workbook wb = new XSSFWorkbook();
    Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    CellStyle style;//  w  w w.  j  a  v  a 2  s  .c  om
    DataFormat df = wb.createDataFormat();

    Font font = wb.createFont();
    font.setFontName("Serif");
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 15);
    style = wb.createCellStyle();
    style.setFont(font);
    styles.put("title", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 10);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(font);
    style.setWrapText(true);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("th", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font);
    style.setWrapText(true);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setFont(font);
    style.setWrapText(true);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-border", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-double", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-right", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-bold", style);

    font = wb.createFont();
    font.setFontName("Serif");
    font.setFontHeightInPoints((short) 9);
    style = wb.createCellStyle();
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setFont(font);
    style.setDataFormat(df.getFormat("d.mm.yyyy h:MM"));
    style.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    styles.put("td-date", style);

    Sheet sheet = wb.createSheet();
    sheet.setFitToPage(true);

    Cell cell;

    int maxRows = 0;
    for (int r = 0; r < table.length; r++) {
        Row row = sheet.createRow(r);
        if (r == 0) {
            row.setRowStyle(styles.get("th"));
        }

        int rows = 1;
        for (int c = 0; c < table[r].length; c++) {
            cell = row.createCell(c);
            String s = table[r][c];
            if (s == null)
                continue;
            rows = Math.max(rows, s.split("\n").length);
            try {
                if (exportMode == ExportMode.HEADERS_TOP && r == 0) {
                    cell.setCellStyle(styles.get("th"));
                    cell.setCellValue(s);

                } else if (exportMode == ExportMode.HEADERS_TOPLEFT && (r == 0 || c == 0)) {
                    if (r == 0 && c == 0) {
                        cell.setCellStyle(styles.get("td"));
                    } else {
                        cell.setCellStyle(styles.get("th"));
                    }
                    cell.setCellValue(s);
                } else if (types[c] == Double.class) {
                    cell.setCellStyle(styles.get("td-double"));
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(Double.parseDouble(s));
                } else if (types[c] == String.class) {
                    cell.setCellStyle(
                            styles.get(exportMode == ExportMode.HEADERS_TOPLEFT ? "td-border" : "td"));
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(s);
                } else {
                    cell.setCellStyle(styles.get("td-right"));
                    cell.setCellValue(s);
                }
            } catch (Exception e) {
                cell.setCellStyle(styles.get("td"));
                cell.setCellValue(s);
            }
        }
        maxRows = Math.max(maxRows, rows);
        row.setHeightInPoints(rows * 16f);

    }

    // Add footer notes
    if (footerData.size() > 0) {
        Row row = sheet.createRow(table.length);
        row.setHeightInPoints((footerData.size() * sheet.getDefaultRowHeightInPoints()));
        cell = row.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), //first row (0-based)
                row.getRowNum(), //last row  (0-based)
                0, //first column (0-based)
                table[0].length - 1 //last column  (0-based)
        ));
        //for ( String data : footerData ) {
        style = wb.createCellStyle();
        style.setWrapText(true);
        cell.setCellStyle(style);
        cell.setCellValue(MiscUtils.flatten(footerData, "\n"));
        //}
    }
    footerData.clear();

    autoSizeColumns(sheet);
    if (table.length > 0) {
        for (int c = 0; c < table[0].length; c++) {
            if (sheet.getColumnWidth(c) > 10000)
                sheet.setColumnWidth(c, 3000);
        }
    }

    if (exportMode == ExportMode.HEADERS_TOPLEFT) {
        for (int r = 1; r < table.length; r++) {
            sheet.getRow(r).setHeightInPoints(maxRows * 16f);
        }
    }

    File reportFile = IOUtils.createTempFile("export_", ".xlsx");
    FileOutputStream out = new FileOutputStream(reportFile);
    wb.write(out);
    wb.close();
    out.close();
    Desktop.getDesktop().open(reportFile);
}