public void downloadExcel(Class c, List list, HttpServletResponse response, String fileName) {
try {
ExportParams exportParams = new ExportParams();
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, c, list);
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
response.setHeader("content-Type", "application/vnd.ms-excel");
workbook.write(response.getOutputStream());
workbook.close();
response.flushBuffer();
} catch (Exception e) {
log.error(e.getMessage());
throw new CheckException("导出excel出错!");
}
}
导出的传输类,在需要导出的字段上添加注解 @Excel(name=“物料编码”):
@Data
public class AgencyConsumableDto{
@Excel(name="物料编码")
@ApiModelProperty(value = "物料编码")
private String consumableCode;
@Excel(name="物料名称")
@ApiModelProperty(value = "物料名称")
private String consumableName;
@Excel(name="物料分类")
@ApiModelProperty(value = "物料分类名称")
private String consumableTypeName;
@Excel(name="品牌")
@ApiModelProperty(value = "品牌")
private String brand;
@Excel(name="规格型号")
@ApiModelProperty(value = "规格型号")
private String model;
@Excel(name="单位")
@ApiModelProperty(value = "单位")
private String unit;
@Excel(name="物料条码")
@ApiModelProperty(value = "物料条码")
private String barCode;
@Excel(name="采购员")
@ApiModelProperty(value = "采购员")
private String buyer;
@Excel(name="供应商")
@ApiModelProperty(value = "供应商")
private String supplier;
@Excel(name="成本计算方法")
@ApiModelProperty(value = "成本计算方法")
private String computingMethod;
}
测试:
@ApiOperation("导出全部耗材")
@EmployeePermission("consumable:agencyConsumable:exportAllConsumable")
@GetMapping("/exportAllConsumable")
public Result exportAllConsumable(HttpServletResponse response) throws Exception {
List<AgencyConsumableDto> expList = agencyConsumableService.getAllConsumable();
try {
ExcelUtil.downloadExcel(AgencyConsumableDto.class,expList,response,"耗材_"+System.currentTimeMillis()+".xls");
} catch (Exception e) {
log.error(e.getMessage());
throw new OperationFailedException("导出全部耗材失败");
}
return Result.success();
}