[英]How to add custom SheetDataWriter on Apache poi SXSSFWorkbook?
[英]How to use vlookup or formulas in SXSSFWorkbook with Apache POI?
我是Java開發人員。 我正在嘗試使用Apache POI庫的SXSSFWorkbook
類編寫一個較大的xlsx
文件(Excel)。
由於沒有超過200000行,我沒有選擇寫大文件。 但我需要在外部工作表中使用一些公式或vlookup。 當我使用時:
cell.setCellFormula(formulasString);
但是它不起作用並且返回0值。
問:如何在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");
}
}
請給我建議。 謝謝。
不幸的是,SXSSFWorkbook不支持3.12版中的公式。 我發現這在代碼中也是如此,但是,我沒有看到任何與此相關的官方POI文檔。
用於公式評估的POI文檔包含一些用於在創建單元格之后評估公式的示例代碼。 它說它適用於XSSFWorkbook和HSSFWorkbook實現,但沒有提及SXSSFWorkbook。
我嘗試在示例代碼中使用SXSSFWorkbook並收到異常。 查看該異常,很明顯,盡管POI文檔中未明確說明,但是SXSSFWorkbook無法評估公式。
Unexpected type of cell: class org.apache.poi.xssf.streaming.SXSSFCell. Only XSSFCells can be evaluated.
根據您的問題以及注釋中提供的信息,您的問題是您使用的Apache POI版本太舊。 因此,當您嘗試評估SXSSF單元時會出現異常。 如公式評估文檔末尾所述 ,對於SXSSF公式評估,您需要使用3.13 beta 2或更高版本。
另一個潛在的問題-公式評估不僅需要將公式所在的單元格保存在內存中,還需要其引用的任何其他單元格以及它們引用的任何其他單元格。 這可能會導致您出現問題,具體取決於您的vlookup嘗試調用的區域范圍。 vlookup所需的所有單元必須在當前窗口中可用,並且不刷新到磁盤。 因此,您可能需要簡化公式和/或增加窗口大小,以確保每個vlookup單元格都能找到其在評估時所依賴的所有單元格的值。
wb.setForceFormulaRecalculation(true);
在執行wb.write(out)之前設置此項,然后打開文件excel..excel重新計算並獲得計算出的輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.