使用poi进行excel导入并解析插入数据库
生活随笔
收集整理的這篇文章主要介紹了
使用poi进行excel导入并解析插入数据库
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言
最近還得寫excel的導入導出,結果還是得百度,雖然都能看懂,但是還是想記錄下來這些東西
正文
1. 導入jar包
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version> </dependency>2. 開始導入
@RequestMapping(value = "importUsers",method = RequestMethod.POST)public Map<String,Object> importUsers(MultipartFile userFile){Map<String,Object> resultMap = new HashMap<>();if(userFile == null || userFile.isEmpty()){resultMap.put("success", false);resultMap.put("msg", "數(shù)據(jù)文件不存在");return resultMap;}//開啟新的線程來處理導入,并使用callback接受結果FutureTask<Map<String,Object>> task = new FutureTask<>(()->userService.importUsers(userFile));new Thread(task).start();try {resultMap = task.get();} catch (Exception e) {e.printStackTrace();}return resultMap;}
3. 業(yè)務層
@Overridepublic Map<String, Object> importUsers(MultipartFile userFile) {Map<String,Object> resultMap = new HashMap<>();try {//獲取文件的輸入流InputStream inputStream = userFile.getInputStream();//根據(jù)不同類型excel創(chuàng)建book頁。String fileName = userFile.getOriginalFilename();Workbook book = null;if(fileName.endsWith(XLSX)){book = new XSSFWorkbook(inputStream);}else if(fileName.endsWith(XLS)){book = new HSSFWorkbook(inputStream);}else{resultMap.put("success", false);resultMap.put("msg", "文件格式有誤!");return resultMap;}if(book != null){//第一個工作簿Sheet sheet = book.getSheetAt(0);//將結果轉換成集合List<User> users = convert(sheet);for (User u : users) {userMapper.insert(u);}System.out.println(users);}resultMap.put("success", true);resultMap.put("msg", "上傳成功!");return resultMap;} catch (IOException e) {e.printStackTrace();}return resultMap;}/**
* 將每行數(shù)據(jù)封裝成一個對象
*/ private List<User> convert(Sheet sheet){
List<User> userList = new ArrayList<>();
for (int i = 2; i <= sheet.getLastRowNum() ; i++) {
//第一行,第二行跳過,是記錄名和字段名,從第三行開始
Row row = sheet.getRow(i);
User user = new User();
Iterator<Cell> iterator = row.cellIterator();
while (iterator.hasNext()){
Cell cell = iterator.next();
if(cell.getColumnIndex() == 1){
//第二列,類型設置為string,然后賦值給name
cell.setCellType(CellType.STRING);
user.setPhone(cell.getStringCellValue());
}
if(cell.getColumnIndex() == 3){
//第三列,時間格式
if(DateUtil.isCellDateFormatted(cell)){
Date date = cell.getDateCellValue();
user.setCreateDate(date);
}
}
if(cell.getColumnIndex() == 2){
//第二列,類型設置為string,然后賦值給name
cell.setCellType(CellType.STRING);
user.setPassword(cell.getStringCellValue());
}
}
userList.add(user);
}
return userList;
} ?
到現(xiàn)在為止,已經實現(xiàn)了excel的導入了!
需要注意的是:這里必須根據(jù)模板來進行數(shù)據(jù)的取出并分別賦值給不同的屬性。
?
轉載于:https://www.cnblogs.com/chenmc/p/9356324.html
總結
以上是生活随笔為你收集整理的使用poi进行excel导入并解析插入数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html基础1-基本语法/段落标签/特殊
- 下一篇: Flask详解