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

时间:2017-01-26 15:25:05

标签: java excel apache-poi

我正在尝试使用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");

    }


} 

Image1; Image2; Image3

我相信代码很好,因为每次执行代码时," Date Modified"显示最新的时间戳;所以我怀疑可能存在Microsoft Office(Excel)或Apache POI版本控制的问题。

你能帮忙吗?

1 个答案:

答案 0 :(得分:3)

创建工作表,行和单元格后,需要将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();
}