1. 程式人生 > 其它 >【Javaweb】poi實現通過上傳excel表格批量匯入資料到資料庫

【Javaweb】poi實現通過上傳excel表格批量匯入資料到資料庫

轉自:https://www.cnblogs.com/kyliechen/p/10732760.html

1.匯入poi相關jar包

對於只操作2003及以前版本的excel,只需要匯入poi-XXX.jar ,如果還需要對2007及以後版本進行操作,則需要匯入

poi-ooxml-XXX.jar

poi-ooxml-schemas-XXX.jar

2.讀取excel檔案

ImportExcel工具類

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 { // abc.xls 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; } }

前端:給出上傳連結

<div class="layui-form-item">
            <label class="layui-form-label">選擇檔案</label>
            <div class="layui-input-block">
                <input type="file" name="mFile" id="no1" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <input class="layui-btn" style="margin-left: 10%"  id="btn1" type="submit" value="確認匯入">
        </div>

後臺controller層處理接收的excel檔案

@RequestMapping("/staff/import.do")
    @ResponseBody
    public JsonBean importExcel(@RequestParam MultipartFile mFile){
        try {
            String fileName = mFile.getOriginalFilename();
            // 獲取上傳檔案的輸入流
            InputStream inputStream = mFile.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<Staff> list = objMapper.readValue(infos, new TypeReference<List<Staff>>() {});

            // 批量新增
            staffService.addStaffBatch(list);

            return JsonUtils.createJsonBean(1, null);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            return JsonUtils.createJsonBean(0, e.getMessage());
        }

    }

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

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

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

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