与POI相关的代码块运行缓慢

我有下面的代码块包含循环:

Row row = null; Cell cell = null; String dataVal = null; String[] temp = null; for (int j = 0; j < this.myDataValues.size(); j++) { row = sheet.createRow(rownum++); temp = this.finalRowValues.get(j); for (int i = 0; i < 4; i++) { cell = row.createCell(i); dataVal = temp[i]; if (NumberUtils.isNumber(dataVal)) { double d = Double.valueOf(dataVal); cell.setCellValue(d); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(styles.get("currency")); } else if (isValidDate(dataVal)) { cell.setCellValue(dataVal); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(styles.get("date")); } else { cell.setCellValue(temp[i]); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellStyle(styles.get("data")); } sheet.autoSizeColumn(i); } } 

其中myDataValuesString[]List ,每个String[]对象包含4个值。

我在Rational Application Developer版本8和Apache POI 3.8中运行它。

myDataValues有大约5500个元素,我认为这个值非常小。

但是,此代码块需要花费一个多小时才能运行。

我觉得这有点不对劲。 每个包含4个元素的5500个元素应该运行得非常快,应该是几分钟的问题。 可能的原因是什么? 有没有办法让这个块运行得更快?

机器的可用内存或任何其他此类问题没有任何问题。 一切都按预期工作,我已经validation了它。 问题仅出在此块中。

您的处理速度非常慢,因为您要为每一行调用autoSizeColumn 。 从Javadocs中为autoSizeColumn方法 :

在大型工作表上,此过程可能相对较慢,因此通常只应在处理结束时每列调用一次。

将对autoSizeColumn的调用放在创建行的循环之外,仅在列上for循环。 这将最大限度地减少对此方法的调用并提高性能。

试试这个…

 for (int j = 0; j < this.myDataValues.size(); j++) { row = sheet.createRow(rownum++); temp = this.finalRowValues.get(j); for (int i = 0; i < 4; i++) { cell = row.createCell(i); dataVal = temp[i]; if (NumberUtils.isNumber(dataVal)) { double d = Double.valueOf(dataVal); cell.setCellValue(d); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(styles.get("currency")); } else if (isValidDate(dataVal)) { cell.setCellValue(dataVal); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellStyle(styles.get("date")); } else { cell.setCellValue(temp[i]); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellStyle(styles.get("data")); } } } for (int i = 0; i < 4; i++) { sheet.autoSizeColumn(i); }