java - 如何使用 Apache Poi 库读取 xls 和 xlsx?

标签 java android excel apache apache-poi

我有一个从 Excel 读取数据的应用程序。问题是我只能读取 xlsx 文件。我无法读取 xls 文件。这是我的代码:

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


                }
            });

最佳答案

您可以使用 WorkbookFactory.create 方法创建 Workbook,如下所示:

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

关于java - 如何使用 Apache Poi 库读取 xls 和 xlsx?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687855/

相关文章:

java - 如何为 Spring Boot 应用程序设置 org.hibernate.org.hibernate.FlushMode?

android - onPause() 在调用 mediaplayer.isPlaying() 时崩溃

sql-server - 'Microsoft.ACE.OLEDB.15.0' 提供程序未在本地计算机上注册。 (System.Data) 尝试将 Excel 2013 文件导入 SSMS 18 时

excel - 取消按钮应该退出子菜单

java - 具有自定义比较器的 TreeMap 不会删除条目

java - 如何配置 Spring Boot 以使用两个数据库?

android - Facebook Auth 和 Firebase - 如何在同一 Facebook 应用程序下添加 4 个应用程序?

android - 在三星 S4 中,当我们点击通知时应用程序没有打开

excel - 为什么我得到一个不存在的文件名?

java - 埃拉托色尼筛问题 : handling really big numbers