gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:35:19 37 4
gpt4 key购买 nike

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

我相信代码没有问题,因为每次我执行代码时,“修改日期”都会显示最新的时间戳;所以我怀疑 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();
}

关于java - 使用 Apache POI 写入 excel 会损坏 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876893/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com