gpt4 book ai didi

java - 使用 Apache POI 更新 excel 文件

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:51 26 4
gpt4 key购买 nike

我正在尝试使用 Apache POI 更新现有的 excel 文件。每次运行我的代码时,我都会收到如下所示的错误。我也试过 FileInputStreamNewFile 东西。

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);
}

}

最佳答案

如果你更换

//Update the value of cell
cell = sheet.getRow(row).getCell(col);
cell.setCellValue("Pass");

//Retrieve the row and check for null
HSSFRow sheetrow = sheet.getRow(row);
if(sheetrow == null){
sheetrow = sheet.createRow(row);
}
//Update the value of cell
cell = sheetrow.getCell(col);
if(cell == null){
cell = sheetrow.createCell(col);
}
cell.setCellValue("Pass");

它会起作用的!

关于java - 使用 Apache POI 更新 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32273072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com