使用poi读取上传的excel文件内容
public void saveTypeExcel() {
UploadFile files = this.getFile("files", DateUtil.getNowDateShort());
File file = files.getFile();
String fileName=files.getOriginalFileName();
String hz = fileName.substring(fileName.lastIndexOf(".")+1);
List<List<String>> list = null;
try {
list = ExcelUtil.excelToList(file,hz);
} catch (IOException e) {
e.printStackTrace();
}
for (List<String> strings : list) {
System.out.println(strings);
}
}
这里xls格式需要用HSSFWorkbook;xlsx则需要XSSFWorkbook
public class ExcelUtil {
@SuppressWarnings("resource")
public static List<List<String>> excelToList(File filePath,String hz) throws IOException{
List<List<String>> result = new ArrayList<List<String>>();
Workbook workbook = null;
if (hz.toLowerCase().endsWith("xls")) {
workbook = new HSSFWorkbook(new BufferedInputStream(new FileInputStream(filePath)));
} else {
workbook = new XSSFWorkbook(new BufferedInputStream(new FileInputStream(filePath)));
}
Sheet sheet = workbook.getSheetAt(0);
int maxRowNum = sheet.getLastRowNum()+1;
for (int j = 0; j < maxRowNum; j++) {
List<String> rowList = new ArrayList<>();
Row row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < row.getLastCellNum(); k++) {
String cellStr = row.getCell(k) != null?DbImportExcelUtils.getCellStringValue(row.getCell(k)):"";
rowList.add(cellStr);
}
}
result.add(rowList);
}
return result;
}
}
所需要的jar包:
![jar包](https://i-blog.csdnimg.cn/blog_migrate/9223926c149c53849a8dfd09b2218feb.jpeg)
点击下载所需jar包链接。