java 来自 Apache POI 的 Excel 文件无法由 Excel 女士打开(损坏)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30397347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File Excel From Apache POI Cant Open by Ms Excel (corrupt)
提问by ketelagoreng
I don't know why the file I write using POI cant be opened by Ms Excel 2013, but the file is still readable by POI. (cell value can be changed)
不知道为什么我用POI写的文件Ms Excel 2013打不开,但是POI还是可以读取文件的。(单元格值可以更改)
thisis the error from file
这是来自文件的错误
here is the code
这是代码
FileInputStream fis = null;
try {
fis = new FileInputStream(fileUri); //not error at fileUri
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String urii = fileUri.replace(".xls", "0.xls"); //not error
File fisx = new File(urii);
Workbook workbook = null;
workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String p = cell.getStringCellValue();
TextView a = (TextView) findViewById(R.id.txtUri);
cell.setCellValue(new String("popo"));
String x = cell.getStringCellValue();
TextView b = (TextView) findViewById(R.id.txtFile);
a.setText(p);
b.setText(x);
OutputStream fos = null;
fos = new FileOutputStream(fisx);
workbook.write(fos); //main problem
fos.flush();
fos.close();
Thanks for your help!!
谢谢你的帮助!!
回答by Gagravarr
There are two issues with your code. Firstly this:
您的代码有两个问题。首先这个:
FileInputStream fis = null;
try {
fis = new FileInputStream(fileUri);
As explained in the Apache POI Docs, don't use an InputStream if you have a File!
正如Apache POI 文档中所述,如果您有文件,请不要使用 InputStream!
Secondly, this:
其次,这个:
Workbook workbook = null;
workbook = new HSSFWorkbook(fis);
That will only work for .xls
files, not for .xlsx
ones. Instead, you need to use WorkbookFactorywhich identifies the type and gives you the right workbook for the format
这仅适用于.xls
文件,不适用于文件.xlsx
。相反,您需要使用WorkbookFactory来识别类型并为您提供适合该格式的工作簿
So, change your code to be
因此,将您的代码更改为
File file = new File(fileUri);
Workbook workbook = WorkbookFactory.create(file);
回答by Akash Rajbanshi
The major problem that i see here is:
我在这里看到的主要问题是:
Workbook workbook = null;
workbook = new HSSFWorkbook(fis);
Instead you have to use:
相反,您必须使用:
Workbook workbook = null;
workbook = new XSSFWorkbook(fis);
TO be readable by MS EXCEL 2013.
可被 MS EXCEL 2013 读取。
回答by ketelagoreng
Solved :
解决了 :
by using real android device instead of bluestack emulator, I dont know why, but it works!!
通过使用真正的 android 设备而不是 bluestack 模拟器,我不知道为什么,但它有效!!
Thanks everyone :D
谢谢大家:D
回答by Kerem Kulak
You are calling getSheetAt(0) but you did not create any sheet before (workbook.createSheet(“name”)
您正在调用 getSheetAt(0) 但之前没有创建任何工作表 (workbook.createSheet(“name”)