要想使用java代码调用excle中的数据,需要先导入POI jar包
Apache POI的使用:
1、jar包下载地址:
2、下载后导入到项目中
首先点击项目右键-bulid path-Add Libraries,选择User Library
然后点击User Libraries
最后,新建一个文件夹并导入下载的jar包
3、新建一个class,复制已经封装好的代码到该class中
public static Object[][] getTestDataByExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath + "\\" + fileName);
System.out.println("file is :" + file);
FileInputStream inputstream = new FileInputStream(file);
Workbook workbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if (fileExtensionName.equals(".xlsx")) {
workbook = new XSSFWorkbook(inputstream);
} else if (fileExtensionName.equals(".xls")) {
workbook = new HSSFWorkbook(inputstream);
} else {
throw new IOException("wrong fileName");
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
List<Object[]> records = new ArrayList<Object[]>();
for (int i = 1; i < rowCount + 1; i++) {
Row row = sheet.getRow(i);
String fields[] = new String[row.getLastCellNum()];
for (int j = 0; j < row.getLastCellNum(); j++) {
if (row.getCell(j).getCellType() == 0) {
fields[j] = row.getCell(j).getNumericCellValue() + "";
} else {
fields[j] = row.getCell(j).getStringCellValue();
}
}
records.add(fields);
}
Object[][] results = new Object[records.size()][];
for (int x = 0; x < records.size(); x++) {
results[x] = records.get(x);
}
inputstream.close();
workbook.close();
return results;
}