👏👏👏 哈喽!大家好,我是【学无止境小奇】,一位热爱分享各种技术的博主!😍😍😍 ?【学无止境小奇】的创作宗旨:每一条命令都亲自执行过,每一行代码都实际运行过,每一种方法都真实实践过,每一篇文章都良心制作过。??? ?【学无止境小奇】的博客中所有涉及命令、代码的地方,除了提供图片供大家参考,另外会在图片下方提供一份纯文本格式的命令或者代码方便大家粘贴复制直接执行命令或者运行代码。🤝🤝🤝 ?如果你对技术有着浓厚的兴趣,欢迎关注【学无止境小奇】,欢迎大家和我一起交流。😘😘😘 ??????感谢各位朋友接下来的阅读??????
一、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进行学习使用。
|