简体   繁体   中英

Writing Excel file from Java with apache poi

I'm writing an application which reads data from a Microsoft Access database and writes this data into an Excel Sheet. Everything works fine but not the writing of the new data to the file. Here is the code:

private static XSSFWorkbook readFile(String filename) throws IOException {
    // return new XSSFWorkbook(new FileInputStream(filename));
    InputStream inp = new FileInputStream(filename);
    XSSFWorkbook wb = null;
    try {
        wb = (XSSFWorkbook) WorkbookFactory.create(inp);
    } catch (InvalidFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return wb;
}

public void writeToFile(LinkedList<TimeRowWrapper> list) {

    try {
        // read file
        XSSFWorkbook workbook = readFile(fileName);

        // choose table from index
        XSSFSheet sheet = workbook.getSheetAt(kapaSheetIndex);

        for (Row row : sheet) {
            int rowNum = row.getRowNum();

            // iterate over list for row id
            for (TimeRowWrapper trw : list) {
                if (rowNum == trw.getRowNumber()) {

                    double hour = Math
                            .round(trw.getTotalTime() / 60.0 * 100.) / 100.;
                    Cell cell = row.getCell(timeCol);
                    cell.setCellValue(hour);
                }
            }
        }

        XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);

        FileOutputStream out = new FileOutputStream(fileName);
        workbook.write(out);
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
}

From your comments on your post, I'm assuming what you're doing in the for loop is correct. It looks like you're writing numeric values from the code and you're also writing to the same workbook that you read in. I have a theory that possibly you're writing correctly to the Cell but doing the formula evaluation may be doing some tricky things with the numbers since Excel likes to format types weirdly.

Try writing to a new file instead of the input file and see if that generates a spreadsheet, at least.

Also try seeing what happens when commenting out the line:

XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook); 

The sourcecode I posted was correct. In the Excelfile were some Colums with the withe of 0 - so I tryed to write in a column which was not shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM