文件Excel从Apache POI无法打开由Ms Excel(损坏)

我不知道为什么使用POI编写的文件无法由Excel 2013打开,但该文件仍然可以通过POI读取。 (单元格值可以更改)

这是来自文件的错误

这里是代码

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(); 

谢谢你的帮助!!

你的代码有两个问题。 首先这个:

 FileInputStream fis = null; try { fis = new FileInputStream(fileUri); 

如Apache POI文档中所述,如果您有文件,请勿使用InputStream!

其次,这个:

  Workbook workbook = null; workbook = new HSSFWorkbook(fis); 

这只适用于.xls文件,不适用于.xlsx文件。 相反,您需要使用WorkbookFactory来标识types,并为您提供格式正确的工作簿

所以,改变你的代码

 File file = new File(fileUri); Workbook workbook = WorkbookFactory.create(file); 

我在这里看到的主要问题是:

 Workbook workbook = null; workbook = new HSSFWorkbook(fis); 

相反,你必须使用:

 Workbook workbook = null; workbook = new XSSFWorkbook(fis); 

由MS EXCEL 2013阅读。

解决了 :

通过使用真正的Android设备,而不是bluestack模拟器,我不知道为什么,但它的作品!

谢谢大家:D

解决scheme是使用.xls扩展名而不是.xlsx,如本答案所述