基于SpringBoot-Vue-EasyExcel实现的Excel文件导出

基于SpringBoot-Vue-EasyExcel实现的Excel文件导出

  • 一:easyExcel依赖
  • 二:javaBean
  • 三:Controller
  • 四:vue代码

一:easyExcel依赖

		
			com.alibaba
			easyexcel
			1.1.2-beta5
		

二:javaBean

@Data
public class Users extends BaseRowModel {
    @ExcelProperty(value = {"主键ID"}, index = 0)
    private String id;

    @ExcelProperty(value = {"用户姓名"}, index = 1)
    private String name;

    @ExcelProperty(value = {"用户年龄"}, index = 2)
    private String age;
    }

三:Controller

@Controller
public class ExcelExport {
    @GetMapping("/excel")
    public void  export(String fileName,HttpServletResponse response) throws IOException {
        List list = new ArrayList<>();
        list.add(new Users("1","小明","11"));
        list.add(new Users("2","小红","11"));
        list.add(new Users("3","小白","11"));
        list.add(new Users("4","小绿","11"));
        list.add(new Users("5","小灰","11"));
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        Sheet sheet = new Sheet(1, 0,Users.class);
        //设置自适应宽度
        sheet.setAutoWidth(Boolean.TRUE);
        // 第一个 sheet 名称
        sheet.setSheetName("sheet1");
        writer.write(list, sheet);
        //通知浏览器以附件的形式下载处理,设置返回头要注意文件名有中文
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
        writer.finish();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        out.flush();
    }
}

四:vue代码

            exportExcel () {
                this.$http({
                        method: 'get',
                        url: /excel
                        responseType: 'blob',
                        params:{
                            fileName:"哈哈哈"
                        }
                    }
                ).then(function (response) {
                    let blob = new Blob([response.data])
                    let downloadElement = document.createElement('a');
                    let href = window.URL.createObjectURL(blob); //创建下载的链接
                    downloadElement.href = href;
                    downloadElement.download = '哈哈哈.xlsx'; //下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //点击下载
                    document.body.removeChild(downloadElement); //下载完成移除元素
                    window.URL.revokeObjectURL(href); //释放掉blob对象

                }).catch(function (error) {
                       this.$message.error(error)
                 });
            }

基于SpringBoot-Vue-EasyExcel实现的Excel文件导出_第1张图片
基于SpringBoot-Vue-EasyExcel实现的Excel文件导出_第2张图片

你可能感兴趣的:(SpringBoot,Vue,excel)