使用Apache POI写入excel会损坏excel文件

我正在尝试使用Apache POI写入excel。 代码(下面)执行得很好,但是当我试图打开excel时,显示excel中的数据已经损坏,无法打开。

Excel版本:Microsoft Office Excel 2007和Microsoft Office Excel 2003(都尝试过)

Apache POI版本:3.6

import java.io.FileOutputStream; import java.io.IOException; 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 WriteExcel{ public String FilePath; XSSFWorkbook wb= null; XSSFSheet ws= null; XSSFRow xr=null; XSSFCell xc=null; FileOutputStream fout = null; public WriteExcel(String FilePath) throws IOException { this.FilePath=FilePath; fout=new FileOutputStream(FilePath); wb=new XSSFWorkbook(); wb.write(fout); } //Write to a specific Cell public void writeToCell(String SheetName, int RowNum, int ColNum, String Data) throws IOException { ws=wb.createSheet(SheetName); xr=ws.createRow(RowNum); xc=xr.createCell(ColNum); xc.setCellValue(Data); fout.close(); } public static void main(String[] args) throws IOException { WriteExcel WE= new WriteExcel("E://Learning//Learning//SoapUI//TestFiles//Write.xls"); WE.writeToCell("Sheet1", 2, 2, "Pi"); System.out.println("Written"); } } 

此搜索 ; 镜像2 ; 图像3

我相信代码是好的,因为每次我执行代码时,“修改date”显示最新的时间戳; 所以我怀疑可能有一些与Microsoft Office(Excel)或Apache POI版本相关的东西。

能否请你帮忙?

创build表单,行和单元格后,您需要将Excel写入磁盘。

 public WriteExcel(String FilePath) throws IOException { this.FilePath=FilePath; } //Write to a specific Cell public void writeToCell(String SheetName, int RowNum, int ColNum, String Data) throws IOException { fout=new FileOutputStream(FilePath); wb=new XSSFWorkbook(); ws=wb.createSheet(SheetName); xr=ws.createRow(RowNum); xc=xr.createCell(ColNum); xc.setCellValue(Data); wb.write(fout); fout.close(); }