传入一个文件
public List<User > impUser(MultipartFile file) {
//总行数
int totalRows = 0;
//总条数
int totalCells = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<User > dataLi = new LinkedList<>();
try {
Workbook wb = null;
String fileName = file.getOriginalFilename();//获取文件名
if (fileName.matches("^.+\\.(?i)(xls)$")) {
// Excel 2003
wb = new HSSFWorkbook(file.getInputStream());
} else if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
// Excel 2007/2010
wb = new XSSFWorkbook(file.getInputStream());
}
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
if (totalRows > 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
// 循环Excel行数
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
User user= new User ();
// 循环Excel的列
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) { //第一列
user.setName(cell.getStringCellValue);
}
else if (c == 1){
user.setAge(new BigDecimal(cell.getNumericCellValue()));
}
else if (c == 2){
user.setSex(new BigDecimal(cell.getNumericCellValue()));
}
}
}
dataLi.add(energyConsumption);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataLi;
}
拿到数据通过MyBatis遍历插入到数据库中