繁体   English   中英

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

[英]Writing to an excel using Apache POI corrupts the excel file

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

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

能否请你帮忙?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM