【问题标题】:Writing to an excel using Apache POI corrupts the excel file使用 Apache POI 写入 excel 会损坏 excel 文件
【发布时间】:2017-01-26 15:25:05
【问题描述】:

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

    }


} 

; ;

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

你能帮忙吗?

【问题讨论】:

    标签: java excel apache-poi


    【解决方案1】:

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

    【讨论】:

    • 我以编程方式创建了一个 excel (.xlsx),但发现它已损坏。但在创建了至少一张纸后,它消除了 excel 文件的损坏。
    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多