[英]Excel file created with apache poi (Java) can't be opened on Windows
In my system, I have a class that creates an excel with some data.在我的系统中,我有一个类可以用一些数据创建一个 excel。
Basically I read all String values from a variable ArrayList> and write them in excel cells.基本上我从变量 ArrayList> 中读取所有 String 值并将它们写入 Excel 单元格中。
public void writeData(Data data, int sheetNumber)
throws EncryptedDocumentException, InvalidFormatException, IOException {
org.apache.poi.ss.usermodel.Workbook workbook;
try {
workbook = WorkbookFactory.create(new File(path));
} catch (FileNotFoundException e) {
workbook = new HSSFWorkbook();
}
org.apache.poi.ss.usermodel.Sheet sheet;
try {
sheet = workbook.createSheet("Sheet" + sheetNumber);
} catch (IllegalArgumentException e) {
sheet = workbook.getSheet("Sheet" + sheetNumber);
}
int dataListSize = data.getData().size();
for (int i = 0; i < dataListSize; i++) {
Row row = sheet.createRow(i);
int rowSize = data.getData().get(i).size();
for (int j = 0; j < rowSize; j++) {
row.createCell(j);
row.getCell(j).setCellValue(String.valueOf(data.getData().get(i).get(j)));
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(path));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
workbook.close();
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The code works fine as far as I know, I develop on Ubuntu and always try the code here first, the created excels are fine, and I have no problem at all.据我所知,代码运行良好,我在 Ubuntu 上开发并且总是先在这里尝试代码,创建的 excel 很好,我完全没有问题。
When I take one of these to Windows (XP and 7, tried on both), I can't open any of them using Microsoft Excel.当我将其中一个带到 Windows(XP 和 7,都尝试过)时,我无法使用 Microsoft Excel 打开其中任何一个。
Does anyone have any experience with this?有人对这个有经验么?
Thank you.谢谢你。
As Axel mentioned, the problem was the file extension.正如 Axel 所提到的,问题在于文件扩展名。
I can open the files created this way in Ubuntu (Both 14.04 and 16.04), but not in Windows (7, 8 and 10).我可以在 Ubuntu(14.04 和 16.04)中打开以这种方式创建的文件,但不能在 Windows(7、8 和 10)中打开。
The solution is to use the .xls
extension and NOT .xlsx
, that way I can open and use the files in any OS.解决方案是使用
.xls
扩展名而不是.xlsx
,这样我就可以在任何操作系统中打开和使用文件。
HSSF is the Office 97 *.xls format. HSSF 是 Office 97 *.xls 格式。 (It stands for H orrible S pread s heet F ormat.)
(它代表H orrible S pread s heet F格式。)
} catch (FileNotFoundException e) {
workbook = new HSSFWorkbook();
}
When you did that, you chose the *.xls format.当您这样做时,您选择了 *.xls 格式。 You need to use
XSSFWorkbook
if you want *.xlsx format.如果需要 *.xlsx 格式,则需要使用
XSSFWorkbook
。
https://poi.apache.org/components/spreadsheet/quick-guide.html#NewWorkbook https://poi.apache.org/components/spreadsheet/quick-guide.html#NewWorkbook
https://poi.apache.org/components/spreadsheet/ https://poi.apache.org/components/spreadsheet/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.