[英]After using Apache POI to edit and existing Excel file, the formulas that use does cells disappear
我正在使用 Apache POI 來編輯現有文件。 該文件包含多個公式,這些公式使用將通過 Apache 輸入的數字。 這就是我遇到問題的地方,當輸入一個數字並且在公式中使用該單元格時,文件被損壞並且公式消失了。 這里 0 的公式是 C7+D7、C8+D8 等。這里 0 的公式變成了正常的 0,公式丟失了。
這是我用來寫入 excel 文件的代碼:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class write {
public static void main(String[] args) {
String excelFilePath = "C:\\Users\\jose_\\IdeaProjects\\writeExcel\\src\\JavaBooks.xlsx";
try {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
/*Cell cell2Update = sheet.getRow(1).getCell(3); // This updates a specific cell: row 0 cell 3
cell2Update.setCellValue(49);*/
Object[][] bookData = {
{2, 17},
{3, 27},
{4, 33},
{5, 44},
};
// int rowCount = sheet.getLastRowNum(); // Gets the last entry
int rowCount = 5;
for (Object[] aBook : bookData) {
Row row = sheet.createRow(++rowCount);
int columnCount = 1;
int lote = 1;
Cell cell = row.createCell(columnCount);
//cell.setCellValue(rowCount); // This sets the index for each entry
cell.setCellValue(lote);
for (Object field : aBook) {
cell = row.createCell(++columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream("C:\\Users\\jose_\\IdeaProjects\\writeExcel\\src\\JavaBooks.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException ex) {
ex.printStackTrace();
}
}
}
有沒有辦法解決這個問題,還是我需要通過 Apache POI 再次設置所有公式?
您收到錯誤是因為使用代碼行Row row = sheet.createRow(++rowCount);
您總是創建新的空行,因此您刪除了這些行中的所有單元格。 因此,您還刪除了包含公式的單元格。 這樣做會破壞計算鏈。 這就是Excel
GUI
通過消息告訴您的內容。
你不應該這樣做。 相反,您應該始終嘗試首先使用Sheet.getRow
獲取行。 僅當返回null
時,您才需要創建該行。
...
//Row row = sheet.createRow(++rowCount);
Row row = sheet.getRow(rowCount); if (row == null) row = sheet.createRow(rowCount); rowCount++;
...
另外請閱讀公式的重新計算。 因此,在更改公式中引用的單元格后,請始終執行workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
或使用workbook.setForceFormulaRecalculation(true);
將重新計算委托給Excel
; .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.