我想使用Apache POI更新現有的Excel文件。每次運行我的代碼時,都會收到如下所示的錯誤消息。我也試過FileInputStreamNewFile的東西。使用Apache POI更新Excel文件
Exception in thread "main" java.lang.NullPointerException
at com.gma.test.WriteExcelTest.writeXLSXFile(WriteExcelTest.java:26)
at com.gma.test.WriteExcelTest.main(WriteExcelTest.java:44)
請找到下面的代碼。感謝你的幫助。
package com.gma.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcelTest {
public static void writeXLSXFile(int row, int col) throws IOException {
try {
FileInputStream file = new FileInputStream("C:\\Anuj\\Data\\Data.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(row).getCell(col);
cell.setCellValue("Pass");
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\Anuj\\Data\\Data.xlsx"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
writeXLSXFile(3, 3);
}
}
檢查sheet.getRow(行)不爲空,然後如果你問一個行單元格不設置值 –
前空|沒有定義的單元格,你會得到一個空值! –