一、Java打印Excel
Java打印Excel
1.1、引入依赖
<!-- easy poi依赖 --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>4.1.0</version> </dependency>
1.2、在需要打印的对象属性上加注解@Excel
1.如果属性是单个字段则加@Excel注解,
2.如果是属性是对象则加@ExcelEntity,并且所引用的属性对象里面也需要加上@Excel注解
3.如果感觉字段的值比较长,可以设置宽度 width设置
4.如果有特殊格式,例如日期,可以使用format
@ApiModelProperty(value = "合同起始日期") @JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai") @Excel(name = "合同起始日期",width = 20,format = "yyyy-MM-dd") private LocalDate beginContract; @ApiModelProperty(value = "合同终止日期") @JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai") @Excel(name = "合同终止日期",width = 20,format = "yyyy-MM-dd") private LocalDate endContract; @ApiModelProperty(value = "工龄") private Integer workAge; @ApiModelProperty(value = "工资账套ID") private Integer salaryId; @ApiModelProperty(value = "民族") @TableField(exist = false) @ExcelEntity(name = "民族") private Nation nation; @ApiModelProperty(value = "政治面貌") @TableField(exist = false) @ExcelEntity(name = "政治面貌") private PoliticsStatus politicsStatus;
1.3、打印接口
定义打印接口,接口中将查出来的数据放入ExportParams和Workbook,最后输出
@ApiOperation(value = "导出员工数据") @GetMapping(value = "/export",produces = "application/octet-stream") public void exportEmployee(HttpServletResponse response){ List<Employee> list = employeeService.getEmployee(null); ExportParams params = new ExportParams("员工表","员工表", ExcelType.HSSF); Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list); ServletOutputStream out = null; try { response.setHeader("content-type","application/octet-stream"); response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8")); out = response.getOutputStream(); workbook.write(out); } catch (IOException e){ e.printStackTrace(); }finally { if(null!=out){ try { out.close(); }catch (IOException e){ e.printStackTrace(); } } }
1.4、总结
本次使用的是easy poi开源插件实现的打印功能,具体的使用方法可以在码云上搜索easy poi进行学习使用。