• SpringBoot + Poi + ajax 实现导出 excel


    SpringBoot + Poi + ajax 实现导出 excel

    当我们有导出 excel 的需求时,相信有不少人第一想到的就是 POI 的插件了,那在这里就做简单的示例。

    1、pom.xml 引入依赖

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.0.1</version>
    </dependency>
    

    2、编写测试接口

    @Override
    public void exportUser(HttpServletResponse response) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("员工信息表");
    
        //设置文件名称
        String fileName = "员工信息" + LocalDate.now() + ".xls";
        //设置表头
        String[] headerList = {"序号", "编号", "姓名", "状态"};
        HSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < headerList.length; i++) {
            HSSFCell cell = headerRow.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headerList[i]);
            cell.setCellValue(text);
        }
        //设置数据行,存放数据到表中
        int rowColumn = 1;
        List<User> userList = userDao.selectList(new EntityWrapper<User>());
        for(User user : userList) {
            HSSFRow dataRow = sheet.createRow(rowColumn);
            dataRow.createCell(0).setCellValue(development.getId());
            dataRow.createCell(1).setCellValue(development.getNumber());
            dataRow.createCell(2).setCellValue(development.getName());
            dataRow.createCell(3).setCellValue(development.getStatus());
            rowColumn++;
           
        }
        //设置流格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
        workbook.close();
    }       
    

    3、ajax 获取流文件实现导出

    $.ajax({
        type: "POST",
        data: JSON.stringify(searchData),
        contentType: 'application/json',
        //设置响应类型
        xhrFields: {responseType: "blob"},
        url: "/test/lin/exportUser",
        success: function (result) {
            const link = document.createElement('a');
            let blob = new Blob([result], {type: 'application/vnd.ms-excel'});
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', "员工信息表.xls");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link)
        }
    });
    

    最终导出结果如下:

    image-20220531175129943

  • 相关阅读:
    NLPIR大数据语义系统文本数据分析挖掘平台
    NLPIR:中文语义挖掘是自然语言处理的关键
    NLPIR-JZSearch智能搜索深层挖掘大数据资源
    NLPIR智能Protege知识图谱实现多场景应用
    DotNet加密方式解析--散列加密
    SSO单点登录PHP简单版
    xss框架基础框架实现
    Kafka Offset Storage
    C#如何使用ES
    模拟Vue之数据驱动
  • 原文地址:https://www.cnblogs.com/CF1314/p/16331514.html
Copyright © 2020-2023  润新知