1. 程式人生 > 實用技巧 >上傳excel表格批量匯入資料到資料庫

上傳excel表格批量匯入資料到資料庫

控制層

@RequestMapping(value="upload")
    @ResponseBody
    public String  upload(MultipartFile file){
        try {
             String fileName = file.getOriginalFilename();
             // 獲取上傳檔案的輸入流
             InputStream inputStream = file.getInputStream();
             // 呼叫工具類中方法,讀取excel檔案中資料
             List<Map<String, Object>> sourceList = ImportExcel.readExcel(fileName, inputStream);
             // 將物件先轉為json格式字串,然後再轉為List<SysUser> 物件
             ObjectMapper objMapper = new ObjectMapper();
             String infos = objMapper.writeValueAsString(sourceList);
             // json字串轉物件
             List<User> list = objMapper.readValue(infos, new TypeReference<List<User>>() {});
             // 批量新增
             userService.addUsers(list);
             return "success";
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             return e.getMessage();
         }
    }

ImportExcel工具類

package com.example.demo.User.service;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportExcel {

    public static boolean isXls(String fileName){
        // (?i)忽略大小寫
        if(fileName.matches("^.+\\.(?i)(xls)$")){
             return true;
         }else if(fileName.matches("^.+\\.(?i)(xlsx)$")){
             return false;
         }else{
             throw new RuntimeException("格式不對");
         }
     }

     public static List<Map<String, Object>> readExcel(String fileName, InputStream inputStream) throws Exception{
         boolean ret = isXls(fileName);
         Workbook workbook = null;
         // 根據字尾建立不同的物件
         if(ret){
             workbook = new HSSFWorkbook(inputStream);
         }else{
             workbook = new XSSFWorkbook(inputStream);
         }
         Sheet sheet = workbook.getSheetAt(0);
         // 得到標題行
         Row titleRow = sheet.getRow(0);
         int lastRowNum = sheet.getLastRowNum();
         int lastCellNum = titleRow.getLastCellNum();
         List<Map<String, Object>> list = new ArrayList<>();
         for(int i = 1; i <= lastRowNum; i++ ){
             Map<String, Object> map = new HashMap<>();
             Row row = sheet.getRow(i);
             for(int j = 0; j < lastCellNum; j++){
                     // 得到列名
                     String key = titleRow.getCell(j).getStringCellValue();
                     Cell cell = row.getCell(j);
                     cell.setCellType(CellType.STRING);

                     map.put(key, cell.getStringCellValue());
                 }
             list.add(map);
         }
         workbook.close();
         return list;
     }
}

【注意】excel每個列名要和資料庫欄位名一致!!

對於有date型別的資料,excel輸入2019-12-12會變為日期格式資料,日期型別傳到後臺時會轉成字串,其格式會出錯,就無法轉換Date型別,

所以Excel表格一定要將時間相關資料用文字格式儲存!!!

資料庫對應實體類與時間相關屬性要新增@DateTimeFormat(pattern="yyyy-MM-dd")註解