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

posted @ 2022-05-31 18:01  MyDistance  阅读(686)  评论(2编辑  收藏  举报