其他分享
首页 > 其他分享> > springboot整合Excel导出数据

springboot整合Excel导出数据

作者:互联网

最近项目中用到了将表单数据导出为excel,本次使用的工具是EasyExcel

(1)导入所需的pom文件

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>

(2)编写数据传输类,用于封装数据,如下所示:

@Data
public class PaperworkProcessExcelDto {
    @ExcelProperty(value = "序号")
    private String id;
    @ExcelProperty(value = "经营者名称")
    private String enterpriseName;
    @ExcelProperty(value = "行业类别")
    private String industryName;
    @ExcelProperty(value = "任务分配")
    private String mechanismNames;
    @ExcelProperty(value = "创建时间")
    private Date createTime;
    @ExcelProperty(value = "阶段")
    private String masterState;
}

(3)编写业务代码

 @PostMapping(value = "exportExcel", headers = "Accept=application/octet-stream")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public void exportExcel(HttpServletResponse response, @RequestBody PaperworkProcessRequestDto requestDto) throws Exception {
        Map<string, object=""> objectResult = getObjectResult(new Page<>(), requestDto, false);
        List pageList = new ArrayList<>();
        //过滤选中数据
        String selections = requestDto.getSelections();
        List collect = (List) objectResult.get("collect");
        List selectionList = new ArrayList<>();
        //如果有selections,则只返回对应的数据
        if (oConvertUtils.isNotEmpty(selections)) {
            selectionList = Arrays.asList(selections.split(","));
            for (PaperworkProcessDto paperworkProcessDto : collect) {
                String id = paperworkProcessDto.getId();
                if (selectionList.contains(id)) {
                    EncapsulateData(pageList, paperworkProcessDto);
                }
            }
        } else { //不存在selections,返回所有的数据
            for (PaperworkProcessDto paperworkProcessDto : collect) {
                EncapsulateData(pageList, paperworkProcessDto);
            }
        }
        //添加序号
        for (int i = 0; i < pageList.size(); i++) {
            pageList.get(i).setId(String.valueOf(i + 1));
        }

        //导出Excel
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("任务管理", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet = EasyExcel.writerSheet(0, "sheet").head(PaperworkProcessExcelDto.class).build();
        writer.write(pageList, sheet);
        writer.finish();

    }
	

标签:Excel,springboot,pageList,ExcelProperty,导出,value,private,response,String
来源: https://www.cnblogs.com/wuhuac/p/14804760.html