Apache POI创建的XLSX文件损坏。

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

Apache POI creating corrupt XLSX files

问题

以下是您要翻译的内容:

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

我正在使用Apache POI 4.1.1。

这是我的简单代码:

  1. Workbook wb = new XSSFWorkbook();
  2. Sheet sheet = wb.createSheet("new sheet");
  3. Row row = sheet.createRow(0);
  4. Cell cell = row.createCell(0);
  5. cell.setCellValue("Hellooooo");
  6. FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
  7. try {
  8. wb.write(fo);
  9. fo.flush();
  10. fo.close();
  11. wb.close();
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }

这是错误信息:错误

英文:

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:

  1. Workbook wb = new XSSFWorkbook();
  2. Sheet sheet = wb.createSheet("new sheet");
  3. Row row = sheet.createRow(0);
  4. Cell cell = row.createCell(0);
  5. cell.setCellValue("Hellooooo");
  6. FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
  7. try {
  8. wb.write(fo);
  9. fo.flush();
  10. fo.close();
  11. wb.close();
  12. }catch (Exception e) {
  13. e.printStackTrace();
  14. }

And this is the error message: Error

答案1

得分: 1

使用

  1. org.apache.poi.ss.usermodel.WorkbookFactory

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

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

将会返回一个实例

  1. org.apache.poi.ss.usermodel.Workbook

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

  1. Workbook.write(OutputStream)

解决方案:

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

Use

  1. org.apache.poi.ss.usermodel.WorkbookFactory
  2. //Parameter indicates whether you want to create an XSSF formatted file or not
  3. WorkbookFactory.create(true); //true creates XSSF formatted file

will return you an instance of

  1. org.apache.poi.ss.usermodel.Workbook

Then you can write to the file using

  1. Workbook.write(OutputStream)

Solution:

  1. try (Workbook wb = WorkbookFactory.create(true)) {
  2. Sheet sheet = wb.createSheet("new sheet");
  3. Row row = sheet.createRow(0);
  4. Cell cell = row.createCell(0);
  5. cell.setCellValue("Hellooooo");
  6. try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
  7. wb.write(fos);
  8. }
  9. }

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:

确定