easyExcle 打通前后台POST方式下载

后端

 @PostMapping("download")
    public void download(HttpServletResponse response,@RequestBody List<List<String>> list) throws IOException {
        //List> list = dataList();
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为蓝色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());

        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)16);
        headWriteCellStyle.setWriteFont(headWriteFont);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                //加载样式
                .registerWriteHandler(horizontalCellStyleStrategy)
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 这里放入动态头
                .head(getHeader(list)).sheet("模板")
                // 当然这里数据也可以用 List> 去传入
                .doWrite(getData(list));
    }
    private List<List<String>> getHeader(List<List<String>> list){
        List<List<String>> header = new ArrayList();

        list.get(0).forEach(e->{
            List<String> item = new ArrayList();
            item.add(e);
            header.add(item);
        });
        return header;
    }

    private List<List<String>> getData(List<List<String>> list){
        Iterator<List<String>> iterator = list.iterator();

        iterator.next();
        iterator.remove();

        return list;
    }

前端
jquery 版本一定要注意,坑死我了

//post请求下载文件例子 前台   jquery 3.4.x   jquery版本决定了responseType 怎么设置
$.ajax({
                url: 'http://localhost:8080/excle/download', // url为请求接口连接
                    type: 'post',
                contentType: "application/json",
                data: JSON.stringify([
                    ['萬鋼', 'asdfdsal', '23'],
                    [4, 5, 6],
                    [7, 8, '拉跨境電商立刻發酵度搜一法違反了可能為']
                ]),
                headers: {
                    'Accept': 'application/json'
                },
                xhrFields: {
                    responseType: "arraybuffer",
                },
              
                success: function (res) {
                     console.log(res)
                    //downloadFile(res, fileName);  // res为后端传来的文件流
                    let blob = new Blob([res], {
                        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    });
                    let link = document.createElement("a");
                    link.href = window.URL.createObjectURL(blob);
                    link.download = 'test';
                    link.click();
                    document.body.removeChild(link) // 下载完成移除元素
                    window.URL.revokeObjectURL(link.href);// 释放掉blob对象
                },
                error: function (res) {
                    console.log('失败')
                }
            });

你可能感兴趣的:(java基础,javascript,前端,json,easyexcle,spring,boot)