我想使用Java和apache库poi将String写入现有的Excel文件单元格。这是我的方法:
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();
}
}
我的 Excel 文件中没有错误,但“已导入”文字不可用。
答案 0 :(得分:0)
确保您的文件存在,可写并且具有正确的Excel版本。在那之后你应该改变你的代码,因为你得到的是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();
}
}
更好的做法就是把关闭点放在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();
}