1.在pom文件中添加poi依賴:
<!--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>
2.主要代碼
(1)student類
import lombok.Data; @Data public class Student { private String id; private String name; private int age; private String birthday; private String school; private String mother; private String createTime; private int pageNum; private int pageSize; }
(2)controller層
/** * 通過導入excel文件,讀出每個單元格的內容。 * InputStream來自於文件上傳時的MultipartFile對象 */ @ApiOperation("季測評-導入接口") @PostMapping(value = "importSeasonTest") public ResponseEntity<Object> importSeasonTest(@RequestParam MultipartFile file, @RequestParam String name){ return ResponseEntity.ok(uploadService.importSeasonTest(file,name)); }
(3)service層
public Object importSeasonTest(MultipartFile file, String name) { String[] WAGES_HEAD_CH = {"姓名", "年齡", "生日", "學校", "父母"};//表頭 String[] WAGES_HEAD_EN = {"name", "age", "birthday", "school", "mother"};//表頭對應參數 List<Map<String, String>> dataList = ExcelUpload.upload(file, WAGES_HEAD_CH, WAGES_HEAD_EN); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式 List<Student> studentList = new ArrayList<>(); for (Map<String, String> item : dataList) { Student student = new Student(); student.setName(name); student.setBirthday(item.get("birthday")); student.setAge((int) Double.parseDouble(item.get("age"))); student.setSchool(item.get("school")); student.setMother(item.get("mother")); student.setCreateTime(df.format(new Date())); studentList.add(student); } int insertCount = uploadMapper.addStudentData(studentList); return insertCount; }
(4)Mapper層
int addStudentData(List<Student> studentList);
(5)xml層
<insert id="addStudentData"> insert into student ( id, name, age, birthday, school, mother, create_time )values <foreach collection="list" item="item" index="index" separator="," > ( replace(uuid(), '-', ''), #{item.name}, #{item.age}, #{item.birthday}, #{item.school}, #{item.mother}, #{item.createTime} ) </foreach> </insert>
(6)配置文件ExcelUpload
import com.example.demo.exception.CustomException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ExcelUpload { public static List<Map<String, String>> upload(MultipartFile file, String[] WAGES_HEAD_CH, String[] WAGES_HEAD_EN) { List<Map<String, String>> rows = new ArrayList<>(); //獲取文件名稱 String fileName = file.getOriginalFilename(); try { //獲取輸入流 InputStream in = file.getInputStream(); //判斷excel版本 Workbook workbook = null; if (ExcelUtil.judegExcelEdition(fileName)) { workbook = new XSSFWorkbook(in); } else { workbook = new HSSFWorkbook(in); } //獲取第一張工作表 Sheet sheet = workbook.getSheetAt(0); //獲取表頭(第一行) Row row0 = sheet.getRow(0); if (WAGES_HEAD_CH.length != row0.getPhysicalNumberOfCells()) { throw new CustomException("導入的excel表頭不正確(名稱錯誤)"); } for (int i = 0; i < WAGES_HEAD_CH.length; i++) { if (!WAGES_HEAD_CH[i].equals(String.valueOf(row0.getCell(i)))) { throw new CustomException("導入的excel表頭不正確(名稱錯誤)"); } } //從第二行開始獲取 for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { //獲取每一行 Row sheetRow = sheet.getRow(i); Map<String, String> m = new HashMap<>(); for (int j = 0; j < WAGES_HEAD_EN.length; j++) { if (sheetRow.getCell(j) != null) { m.put(WAGES_HEAD_EN[j], String.valueOf(sheetRow.getCell(j))); } } rows.add(m); } workbook.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return rows; } }
(7)配置文件ExcelUtil
public class ExcelUtil { public static boolean judegExcelEdition(String fileName){ if (fileName.matches("^.+\\.(?i)(xls)$")){ return false; }else { return true; } } }
3.postman測試結果(http://localhost:端口號/file/importSeasonTest)
4.數據庫結果
final:不積跬步,無以至千里.不積小流,無以成江海