easypoi根据传入数据动态导出excel
需求:详情界面有一百个字段,可能只需要导出部分选择的字段
/**
* @Description 导出结计算信息
**/
public void exportTaskCloseoutInfo(HttpServletResponse response, String taskId, List<DynamicTablePo> dynamicTablePoList) {
if (StringUtils.isEmpty(taskId) || CollectionUtils.isEmpty(dynamicTablePoList)) return;
CloseoutVo closeoutVo = new CloseoutVo();
CopyOptions options = CopyOptions.create()
.setIgnoreNullValue(true) // 忽略源对象属性为空的情况
.setIgnoreError(true); // 忽略复制过程中出现的错误
OcYunTuTaskCloseoutReach reachInfo = getReachInfo(taskId);
BeanUtil.copyProperties(reachInfo, closeoutVo, options);
List<CloseoutVo> closeoutVoList = new ArrayList<>();
closeoutVoList.add(closeoutVo);
List<ExcelExportEntity> beanList = new ArrayList<ExcelExportEntity>(dynamicTablePoList.size());
for (DynamicTablePo tablePo : dynamicTablePoList) {
ExcelExportEntity entity = new ExcelExportEntity();
entity.setName(tablePo.getFiledShowName());
entity.setKey(tablePo.getFiledCode());
entity.setWidth(15);//设置宽度
entity.setHeight(30);//设置高度
entity.setWrap(true);//支持换行
beanList.add(entity);
}
try {
String excelName = "计算信息";
ExportParams exportParams = new ExportParams();
//添加表头信息
//ExportParams exportParams = new ExportParams(excelName, "sheet1");
exportParams.setHeight((short) 30);
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, beanList, closeoutVoList);
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName + "导出表", "UTF-8") + ".xls");
response.setCharacterEncoding("UTF-8");
workbook.write(response.getOutputStream());
workbook.close();
} catch (Exception e) {
throw new BusinessException("exportTaskCloseoutInfo error: " + e.getMessage());
}
}
DynamicTablePo:
@Data
public class DynamicTablePo implements Serializable {
@ApiModelProperty(value = "表头名字")
private String filedShowName;
@ApiModelProperty(value = "表头key值")
private String filedCode;
}
模拟传值:
{
"taskId":"2280",
"dynamicTablePoList":[
{"filedShowName":"评论类型",
"filedCode":"sentiment"
}, {"filedShowName":"字段2",
"filedCode":"filed2"
}, {"filedShowName":"字段3",
"filedCode":"filed3"
}
]
}