Apache POI公式评估缓慢

时间:2018-01-10 18:44:18

标签: java excel apache-poi

我有一张包含11张的Excel电子表格。我只使用一张纸而且它有500行。我基本上只是将该表转换为csv文件,但使用管道而不是逗号,并做一些其他的事情,如擦除列标题名称和向每行添加UUID。大多数列是公式,当我添加公式评估行时,它使程序需要大约5分钟来处理。我怎样才能加快公式评估,我做错了什么?

    private static void parse(String inputFile, String outputFile) {

    System.out.println("Started Program");

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
    String formattedTimeStamp = dateFormat.format(timeStamp);

    String file = "";

    try {

        FileInputStream excelFile = new FileInputStream(new File(inputFile));
        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet sheetFinal = workbook.getSheet("Final");
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

        Iterator<Row> iterator = sheetFinal.iterator();

        // Skip the column row
        if(iterator.hasNext()) {
            iterator.next();
        }

        while (iterator.hasNext()) {

            Row currentRow = iterator.next();
            Iterator<Cell> cellIterator = currentRow.iterator();

            UUID uuid = UUID.randomUUID();

            file += uuid + PIPE + formattedTimeStamp + PIPE + inputFile;

            while (cellIterator.hasNext()) {

                Cell currentCell = cellIterator.next();

                if (currentCell.getCellTypeEnum() == CellType.FORMULA) {

                    evaluator.evaluateInCell(currentCell);
                }

                //getCellTypeEnum shown as deprecated for version 3.15
                //getCellTypeEnum ill be renamed to getCellType starting from version 4.0
                if (currentCell.getCellTypeEnum() == CellType.STRING) {

                    file += PIPE + currentCell.getStringCellValue();
                } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {

                    file += PIPE + currentCell.getNumericCellValue();
                } else if (currentCell.getCellTypeEnum() == CellType.BOOLEAN) {

                    file += PIPE + currentCell.getBooleanCellValue();
                }
            }

            file += "\n";
        }

        File newFile = new File(outputFile);

        FileUtils.writeStringToFile(newFile, file);

        newFile.createNewFile();

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

    System.out.println(file);
}

1 个答案:

答案 0 :(得分:0)

如果用户打开excel文件,你可以让excel完成工作。

 workbook.setForceFormulaRecalculation(true);