Apache POI创建的XLSX文件损坏。

huangapple go评论80阅读模式
英文:

Apache POI creating corrupt XLSX files

问题

以下是您要翻译的内容:

我正在尝试创建一个简单的XLSX格式的Excel文件。
我可以创建旧的XLS文件,但是当我尝试创建其他格式的文件时,文件总是损坏的。

我正在使用Apache POI 4.1.1。

这是我的简单代码:

Workbook wb = new XSSFWorkbook();
    	
Sheet sheet = wb.createSheet("new sheet");
            
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
            
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
    			
try {
    			
    wb.write(fo);
    fo.flush();
    fo.close();	
    wb.close();
    			
} catch (Exception e) {
    e.printStackTrace();
}

这是错误信息:错误

英文:

I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.

I'm using Apache POI 4.1.1.

This is my simple code:

Workbook wb = new XSSFWorkbook();
	
Sheet sheet = wb.createSheet("new sheet");
        
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
        
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
		
try {
			
	wb.write(fo);
	fo.flush();
	fo.close();	
	wb.close();
			
}catch (Exception e) {
	e.printStackTrace();
}

And this is the error message: Error

答案1

得分: 1

使用

org.apache.poi.ss.usermodel.WorkbookFactory

参数表示是否要创建XSSF格式的文件

WorkbookFactory.create(true);  // true创建XSSF格式的文件

将会返回一个实例

org.apache.poi.ss.usermodel.Workbook

然后你可以使用以下方法将内容写入文件中

Workbook.write(OutputStream)

解决方案:

try (Workbook wb = WorkbookFactory.create(true)) {
    Sheet sheet = wb.createSheet("new sheet");
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Hellooooo");
    try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
        wb.write(fos);
    }
}
英文:

Use

org.apache.poi.ss.usermodel.WorkbookFactory

//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true);  //true creates XSSF formatted file

will return you an instance of

org.apache.poi.ss.usermodel.Workbook

Then you can write to the file using

Workbook.write(OutputStream)

Solution:

try (Workbook wb = WorkbookFactory.create(true)) {
    Sheet sheet = wb.createSheet("new sheet");
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Hellooooo");
    try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
        wb.write(fos);
    }
}

huangapple
  • 本文由 发表于 2020年9月16日 17:32:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63917145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定