Controller层
@RequestMapping(value = "importExcel", method = RequestMethod.POST)
@ResponseBody
public String importExcel(@ModelAttribute MultipartFile file) throws Exception {
return baseAreaService.importExcel(file);
}
Servvice层
@Transactional(readOnly=false)
public String importExcel(MultipartFile file) throws Exception {
Workbook wb = null;
List<BaseArea> list =new ArrayList<>();
if (file != null) {
// 兼容Excel新版本和老版本,xlsx和xls不兼容
wb = getWorkbook(file);
// 获取第一页数据
Sheet sheet = wb.getSheetAt(0);
// 获取第一页总行数
int rowCount = sheet.getPhysicalNumberOfRows();
// 开始循环取出每一行的数据,
for (int i = 0; i < rowCount; i++) {
BaseArea baseArea= new BaseArea();
// 从第0行开始,因为第0行一般是抬头所以直接从下面一行开始
Row row = sheet.getRow(i);
// 取出每一列的值,从第0列开始
String code = "";//
String name = "";//
Cell cellname = row.getCell(0);
Cell cellmobile = row.getCell(1);
cellname.setCellType(CellType.STRING);
code = cellname.getStringCellValue().trim();
cellmobile.setCellType(CellType.STRING);
name = cellmobile.getStringCellValue().trim();
baseArea.setAreaCode(code);
baseArea.setAreaName(name);
}
}
return "";
}
// 兼容Excel新版本和老版本,xlsx和xls不兼容
public static Workbook getWorkbook(MultipartFile file) throws IOException {
Workbook workbook = null;
String fileName = file.getOriginalFilename();
if (fileName.endsWith("xls")) {
POIFSFileSystem pois = new POIFSFileSystem(file.getInputStream());
workbook = new HSSFWorkbook(pois);
} else if (fileName.endsWith("xlsx")) {
workbook = new XSSFWorkbook(file.getInputStream());
}
return workbook;
}