如何在使用Apache POI的SXSSFWorkbook中使用vlookup或公式?

我是Java开发人员。 我正在尝试使用Apache POI库的SXSSFWorkbook类编写一个大的xlsx文件(Excel)。

由于有超过200000行,我没有select写大文件。 但我需要使用一些公式或Vlookup与外部工作表。 当我使用:

 cell.setCellFormula(formulasString); 

但它不工作,它正在返回0值。

Q-如何使用SXSSFWorkbook的公式?

我的代码 –

 import java.io.FileOutputStream; import junit.framework.Assert; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.streaming.SXSSFWorkbook; public class Demo2 { public static void main(String[] args) throws Throwable { SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk FormulaEvaluator fEvaluator=wb.getCreationHelper().createFormulaEvaluator(); Sheet sh = wb.createSheet(); for(int rownum = 0; rownum < 100000; rownum++) { Row row = sh.createRow(rownum); for(int cellnum = 0; cellnum < 10; cellnum++) { Cell cell = row.createCell(cellnum); String address = new CellReference(cell).formatAsString(); cell.setCellValue(address); } Cell cell1 = row.createCell(12); cell1.setCellType(Cell.CELL_TYPE_FORMULA); String sF = "SUM(10,20,30)"; cell1.setCellFormula(sF); fEvaluator.clearAllCachedResultValues(); Cell cell2 = row.createCell(13); cell2.setCellValue("Test"); } // Rows with rownum < 900 are flushed and not accessible for(int rownum = 0; rownum < 99900; rownum++) { Assert.assertNull(sh.getRow(rownum)); } // ther last 100 rows are still in memory for(int rownum = 99900; rownum < 100000; rownum++) { Assert.assertNotNull(sh.getRow(rownum)); } FileOutputStream out = new FileOutputStream("sxssf.xlsx"); wb.write(out); out.close(); // dispose of temporary files backing this workbook on disk wb.dispose(); System.out.println("Done"); } } 

请给我build议,如果可能的话。 谢谢。

根据您的问题以及评论中提供的信息,您的问题是您使用的是过时的Apache POI版本。 这就是为什么当你尝试评估SXSSF单元时你会遇到exception。 正如方程式评估文档末尾所详述的那样 ,对于SXSSF公式评估,您需要使用3.13 beta 2或更高版本。

还有一个潜在的问题 – 配方评估不仅需要配方中的细胞记忆,而且还需要任何其他的细胞以及它所指的任何细胞。 这可能会导致您的问题,这取决于您的vlookup尝试调用的区域有多宽。 vlookup所需的所有单元必须在当前窗口中可用,而不是刷新到磁盘。 因此,您可能需要简化公式和/或增加窗口大小,以确保每个查找单元格可以在评估时间查找所依赖的所有单元格的值

不幸的是,SXSSFWorkbook不支持版本3.12中的公式。 我发现这在代码中也是如此,然而,我没有看到有关这个的官方POI文档。

公式评估的POI文档中有一些示例代码,用于在单元格创build后评估公式。 它说,它适用于XSSFWorkbook和HSSFWorkbook实现,但没有提到SXSSFWorkbook。

我试图在示例代码中使用SXSSFWorkbook并收到exception。 看一下例外情况,即使没有在POI文件中明确指出,公式也不能由SXSSFWorkbook进行评估。

 Unexpected type of cell: class org.apache.poi.xssf.streaming.SXSSFCell. Only XSSFCells can be evaluated. 

wb.setForceFormulaRecalculation(真);

设置这之前做wb.write(出)文打开文件我excel..excel重新计算和得到计算的输出