[英]Unable to write data into Excel file cell
我想使用Java和apache庫poi將字符串寫入現有的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文件中不可用 。
確保您的文件存在,可寫並且具有正確的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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.