![](https://img.haomeiwen.com/i1461379/e04a54377433a430.png)
pom.xml中依赖
<!--poi依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
其中columns是表格的列
/**
* 读取excel表格数据
*/
public List<Map<String, String>> importExcel(HttpServletRequest request) throws IOException, BusinessException {
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Set<Map.Entry<String, MultipartFile>> set = multipartRequest.getFileMap().entrySet();
for (Map.Entry<String, MultipartFile> multipartFileEntry : set) {
MultipartFile multipartFile = multipartFileEntry.getValue();
String fileName = multipartFile.getOriginalFilename();
InputStream inputStream = null;
Workbook workBook = null;
FileInputStream fis = null;
fis = (FileInputStream) multipartFile.getInputStream();
if (fileName.endsWith("xls")) {
workBook = new HSSFWorkbook(fis);
} else if (fileName.endsWith("xlsx")) {
workBook = new XSSFWorkbook(fis);
} else {
}
Sheet sheet = null;
Row row = null;
List<Map<String, String>> list = new ArrayList<>();
String cellData = null;
String columns[] = {"a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"};
if (workBook != null) {
//获取第一个sheet
sheet = workBook.getSheetAt(0);
//获取最大行数
int rownum = sheet.getPhysicalNumberOfRows();
//获取第一行
row = sheet.getRow(0);
//获取最大列数
int colnum = row.getPhysicalNumberOfCells();
for (int i = 1; i < rownum; i++) {
Map<String, String> map = new LinkedHashMap<String, String>();
row = sheet.getRow(i);
if (row != null) {
for (int j = 0; j < 13; j++) {
cellData = ExcelUtil.getStringCellValue(row.getCell(j));
map.put(columns[j], cellData);
}
} else {
break;
}
list.add(map);
}
}
return list;
}
throw new BusinessException("没有找到文件");
} else {
throw new BusinessException("没有找到文件");
}
}
网友评论