英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论