[英]Unable to write data into Excel file cell
I want to write a String into an existing Excel file cell using Java and apache library poi. 我想使用Java和apache库poi将字符串写入现有的Excel文件单元中。 Here is my method:
这是我的方法:
public void setSuccessMessageInExcellFile(File uploadFile, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(uploadFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet excelSheet = workbook.getSheetAt(0);
HSSFCell cell = excelSheet.getRow(0).getCell(0);
cell.setCellValue("Imported");
fileInputStream.close();
FileOutputStream out = new FileOutputStream(uploadFile);
workbook.write(out);
out.close();
} catch(Exception ex) {
ex.getCause().printStackTrace();
}
}
there is no error but "Imported" text is not available in my Excel file. 没有错误,但是“导入的”文本在我的Excel文件中不可用 。
Be sure that your file exists, writable and has the right Excel version. 确保您的文件存在,可写并且具有正确的Excel版本。 After that you should change your code like that, because you are getting a
NullPointerException
otherwise: 之后,您应该像这样更改代码,因为否则会得到
NullPointerException
:
public void setSuccessMessageInExcellFile(File uploadFile, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(uploadFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet excelSheet = workbook.getSheetAt(0);
HSSFCell cell = excelSheet.createRow(0).createCell(0);
cell.setCellValue("Imported");
fileInputStream.close();
FileOutputStream out = new FileOutputStream(uploadFile);
workbook.write(out);
out.close();
} catch(Exception ex) {
ex.getCause().printStackTrace();
}
}
And better would be putting the closables in the try as argument like that: 更好的方法是将可关闭对象放在try这样的参数中:
try(FileInputStream fileInputStream = new FileInputStream(uploadFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
FileOutputStream out = new FileOutputStream(uploadFile)) {
HSSFSheet excelSheet = workbook.getSheetAt(0);
HSSFCell cell = excelSheet.createRow(0).createCell(0);
cell.setCellValue("Imported");
workbook.write(out);
} catch(Exception ex) {
ex.getCause().printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.