Excel file from Apache POI Cant Open from Ms Excel (damaged)

I do not know why the file that I am writing using the POI can be opened by Ms Excel 2013, but the file is still readable by the POI. (cell value can be changed)

this is a file error

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 the help!

+7
java android excel apache-poi
source share
4 answers

There are two problems in the code. The first is:

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

As explained in the Apache POI Docs, do not use an InputStream if you have a file!

Secondly, these are:

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

This will only work for .xls files, not for .xlsx . Instead, you need to use a WorkbookFactory that identifies the type and gives the correct workbook for the format

So change your code to

 File file = new File(fileUri); Workbook workbook = WorkbookFactory.create(file); 
+6
source share

The main problem that I see here:

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

Instead, you should use:

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

For reading MS EXCEL 2013.

+1
source share

It is decided:

using a real android device instead of bluestack emulator, I don't know why, but it works!

Thanks to everyone: D

0
source share

The solution is to use the .xls and NOT.xlsx extensions as mentioned in this.

0
source share

All Articles