![](/img/trans.png)
[英]Is there any way to read both .xls and .xlsx files using Apache POI?
[英]How to read both xls and xlsx with Apache Poi library?
我有一個從 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
WorkbookFactory.create
,如下所示:
InputStream inp = new FileInputStream(new FileInputStream("/path/to/file.xls"));
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
用於讀取xlsx
文件Workbook workbook = new XSSFWorkbook(inputStream);
用於讀取xls
文件(< 2007)
Workbook workbook = new HSSFWorkbook(inputStream);
無需其他更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.