java 導入excel

使用 layui: js 端

//執行實例
    var uploadInst = upload.render({
        elem: '#btnImport'  // 按鈕id
        , url: Feng.ctxPath +'/geyeDeviceNumPool/uploadExcel'
        ,accept: 'file'
        ,before:function (obj) {
        // 上傳前事件
            layer.load() // 開啓loading
        }
        , done: function (res) {
            //上傳完畢回調
            layer.closeAll('loading'); //關閉loading
            table.reload(GeyeDeviceNumPool.tableId, {
                where: {}, page: {curr: 1}
            });
        }
        , error: function () {
            //請求異常回調
            layer.closeAll('loading'); //關閉loading
        }
    });

後端控制器:
使用 hutool poi

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
	/**
     * 上傳excel填報
     */
    @RequestMapping("/uploadExcel")
    @ResponseBody
    public ResponseData uploadExcel(@RequestPart("file") MultipartFile file) {

        try {
	        // 查看 hutool文檔 , 可進行流讀取, 也可以文件方式, 或者其他方式
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
			// 設置別名映射 , 方便讀取映射爲實體
            reader.addHeaderAlias("設備編碼", "deviceNum");
            reader.addHeaderAlias("設備密碼", "devicePwd");
            reader.addHeaderAlias("設備類型", "deviceType");

			// 是否需要讀取上傳excel的所有sheet內容 
			// 獲取sheet 頁數, 遍歷讀取所有sheet頁的所有內容 
            List<Sheet> sheets = reader.getSheets();
            for (int i = 0; i < sheets.size(); i++) {
                reader.setSheet(i);

                List<GeyeDeviceNumPool> readAll = reader.readAll(GeyeDeviceNumPool.class);

                readAll.stream().forEach(v -> {
                    LambdaQueryWrapper<GeyeDeviceNumPool> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(GeyeDeviceNumPool::getDeviceNum, v.getDeviceNum());
					// 判斷庫中是否存在, 不存在再新增
					// 數據量少使用,  多的話可以考慮把數據先全讀出來, 做計算,
					// 或者考慮使用緩存, 
                    if (geyeDeviceNumPoolService.count(queryWrapper) == 0) {
                        geyeDeviceNumPoolService.save(v);
                    }
                });
            }
        } catch (Exception e) {
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return ResponseData.success();
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章