一、引入依赖
<!-- poi 函数库实现对office文件进行读 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<!-- poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
二、输出对应接口,在实现类中实现:
- 批量导入
private final static String XLS = "xls";
private final static String XLSX = "xlsx";
@SuppressWarnings({
"resource", "unused" })
@Override
public Integer importExcel(MultipartFile staffInfo) throws Exception {
//获得文件名
Workbook workbook = null;
String fileName = staffInfo.getOriginalFilename();
if(fileName.endsWith(XLS)) {
//2003
workbook = new HSSFWorkbook(staffInfo.getInputStream());
log.info("2003-xls");
} else if(fileName.endsWith(XLSX)) {
//2007
workbook = new XSSFWorkbook(staffInfo.getInputStream());
log.info("2007-xlsx");
} else {
throw new Exception("文件不是Excel文件");
}
Sheet sheet = workbook.getSheet("Sheet1");
int rows = sheet.getLastRowNum(); //总行数
if(rows == 0) {
throw new Exception("请填写数据");
}
//错误数据
List<Map<String,Object>> errorData = new ArrayList<>();
for(int i = 1; i<= rows+1; i++) {
Map<String,Object> errorMap = new HashMap<>();
//读取左上端单元格
Row row = sheet.getRow(i);
//行不为空
if(row != null) {
//读取cell
Staff staff = new Staff();
//姓名
String name = String.valueOf(row.getCell