使用apache poi修改现有的excel

时间:2014-02-18 07:41:10

标签: java excel apache-poi

当我修改服务器中的现有excel文件并复制到本地计算机并打开它时,我收到 excel could not open because some content is unreadable, do you want to open and repair this workbook? 以下是我的代码。有人可以建议我如何避免这种情况吗?

File f = new File(directory+"users.xlsx");
FileInputStream fileInputStream = new FileInputStream(f);

workbook = new XSSFWorkbook(fileInputStream);
sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(4);
for(int i = 0; i<5; i++)
{
Cell cell = row1.getCell(i);
cell.setCellValue(formattedDate);
cell.setCellStyle(normalStyle);
}

 FileOutputStream out = new FileOutputStream(f, false);
               workbook.write(out);
               out.close();

一直试图解决8个小时,没有运气。如果有人能够阐明这一点,我将感激不尽。

1 个答案:

答案 0 :(得分:3)

将输出移动到另一个文件,不要忘记关闭输入和输出   并使用此http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/WorkbookFactory.html

File f = new File(directory+"users.xlsx");

FileInputStream fileInputStream = new FileInputStream(f);

Workbook workbook = WorkbookFactory.create(fileInputStream);
fileInputStream.close();
sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(4);
for(int i = 0; i<5; i++)
{
Cell cell = row1.getCell(i);
cell.setCellValue(formattedDate);
cell.setCellStyle(normalStyle);
}

 FileOutputStream out = new FileOutputStream(f, false);
               workbook.write(out);
               out.close();