简体   繁体   中英

How to read both xls and xlsx with Apache Poi library?

I have an app that reads from an excel. The problem is that I only can read xlsx files. I cant read xls files. This is my code:

FileInputStream file = new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+nomeExcel));
                        HSSFWorkbook workbook = new HSSFWorkbook(file);
                        HSSFSheet sheet = workbook.getSheetAt(0);

                        int rowCtr = 34;
                        Row myRow = sheet.getRow(rowCtr++);
                        while (myRow != null) {
                            Cell nif = myRow.getCell(0);
                            Cell marcaexploracao = myRow.getCell(1);
                            Cell numerochip = myRow.getCell(2);
                            Cell marcaauricular = myRow.getCell(3);
                            Cell datanascimento = myRow.getCell(4);

                            bd.addAnimais(numerochip.toString().replace("\u00a0",""),marcaexploracao.toString().trim(),marcaauricular.toString(),datanascimento.toString(),nif.toString(),0,"","","","",0);
                            myRow = sheet.getRow(rowCtr++);
                        }

                    }catch (Exception e){e.printStackTrace(); }

                    Toast.makeText(getApplicationContext(),"Excel importado",Toast.LENGTH_SHORT).show();


                }
            });

You can create Workbook with WorkbookFactory.create method like that:

InputStream inp = new FileInputStream(new FileInputStream("/path/to/file.xls"));
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);

For reading xlsx file
Workbook workbook = new XSSFWorkbook(inputStream);

For reading xls file (< 2007)
Workbook workbook = new HSSFWorkbook(inputStream);

No other changes required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM