1. 程式人生 > 其它 >SpringBoot+EasyExcel+thymeleaf+layui實現Excel上傳下載

SpringBoot+EasyExcel+thymeleaf+layui實現Excel上傳下載

技術標籤:專案實戰經驗javaexcel資料庫

背景:

在後臺系統管理專案中,經常會用到excel的匯入匯出,而Apache POI又顯得比較笨重,因此阿里巴巴封裝了POI,釋出了開源的輕量級的解析、生成excel的框架。

匯入Excel:

前端程式碼:

html:

<div class=" layui-upload-button" style="border:#FFFFFF ;">
    <button type="button" class="layui-btn" id="test1">
        <i class="layui-icon">&#xe67c;</i>匯入成員資訊
    </button>
    <input class="layui-upload" type="file" accept="undefined" id="excelFile" name="excelFile" >
</div>
js:
 function uploadExcel() {
        var formData = new FormData();
        formData.append('excelFile', $('#excelFile')[0].files[0]);
        // formData.append('id', id);//將id追加再id中
        //console.log(formData);
        layer.msg('檔案上傳中', {icon: 16});
        $.ajax({
            type: "post",
            processData: false,
            contentType: false,
            url: "/importExcel",
            data: formData,
            success: function (data) {
                if (data.status == 1) {
                    layer.closeAll('loading');
                    layer.msg(data.msg, {icon: 1, time: 1000});
                    window.parent.location.reload();
                    return false;
                } else {
                    layer.msg(data.msg, {icon: 2, time: 1000});
                }
            }
        });

    }

後臺程式碼:

控制層:

 @Autowired
    private UserService userService;
    @PostMapping("importExcel")
    public ServerResponse importExcel(@RequestParam("excelFile")MultipartFile excelFile){
        try {
            List<User> objects = EasyExcel.read(excelFile.getInputStream(), User.class, null).sheet(0).doReadSync();
            for (int i=0;i<objects.size();i++){
                userService.insertSelective(objects.get(i));//此處呼叫業務層增加方法將資料新增進資料庫,根據自己底層程式碼呼叫(本人所用的是mybatis-plus)
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ServerResponse.buildSuccessMsg("匯入成功,即將重新整理頁面");
    }

生成Excel:

前端程式碼:

​
                    <div class="layui-input-inline">
                        <div class="site-demo-upbar">
                            <div class=" layui-download-button" style="border:#FFFFFF ;">
                                <a class="layui-btn" type="button" href="/export">
                                    <i class="layui-icon">&#xe608;</i>匯出成員資訊
                                </a>
                            </div>
                        </div>
                    </div>

​

後臺程式碼:

 @RequestMapping("/export")
    public String ExporExcel(HttpServletResponse response) throws Exception { //throws IOException {
        ExcelWriter writer = null;
        OutputStream outputStream = response.getOutputStream();
        try {
            //新增響應頭資訊
            response.setHeader("Content-disposition", "attachment; filename=" + "小區資訊表.xls");
            response.setContentType("application/msexcel;charset=UTF-8");//設定型別
            response.setHeader("Pragma", "No-cache");//設定頭
            response.setHeader("Cache-Control", "no-cache");//設定頭
            response.setDateHeader("Expires", 0);//設定日期頭
            EasyExcel.write(outputStream,User.class).sheet("成員資訊統計").doWrite(userService.writeData());
            writer.finish();
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

踩坑:平時見到的彈窗幾乎都是js來觸發的,就習慣性的認為瀏覽器的下載彈窗也是靠js來觸發的,殊不知其是靠後臺程式碼,通過response來觸發。