所需工具
采用alibaba的EasyExcel, EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。 因为我目前用Maven来管理包,所以附上Maven导包代码
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beat1</version>
</dependency>
生成表头
我采用在实体类写注解的方式生成表头,此处用医生的实体类来做演示,此处getter和setter方法不再赘述。需要注意两个点 1.@ExcelProperty(value,index),其中value为列头名称,index为索引 2.需使该实体类继承BaseRowModel类
public class HDoctor extends BaseRowModel {
@ExcelProperty(value = "编号",index = 0)
private Integer d_id;
@ExcelProperty(value = "姓名",index = 0)
private String d_name;
@ExcelProperty(value = "身份证号",index = 0)
private String d_idCard;
@ExcelProperty(value = "手机号码",index = 0)
private String d_phone;
@ExcelProperty(value = "性别",index = 0)
private Integer d_sex;
@ExcelProperty(value = "年龄",index = 0)
private Integer d_age;
@ExcelProperty(value = "科室",index = 0)
private Integer d_keshi;
@ExcelProperty(value = "学历",index = 0)
private Integer d_xueli;
@ExcelProperty(value = "个人简介",index = 0)
private String d_desc;
}
生成数据
因为我在写的是一个SSM项目,所以数据的导出写在Service层 此处需要注意 1.FileOutputStream()中写的是所生成.xlsx文件所在位置,我这里是直接输出到了桌面 2.Sheet sheet1 = new Sheet(1, 0, HDoctor.class);中第三个参数为实体类的类型,即继承了BaseRowModel类的那个类的名字。 3.输入数据格式为list
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
public void ToExcel(Integer[] ids){
List<HDoctor> list = new ArrayList<>();
for (Integer id : ids) {
System.out.println(id);
HDoctor doctor = doctorMapper.selectByPrimaryKey(id);
list.add(doctor);
}
try (OutputStream out = new FileOutputStream("C:\\Users\\Cave\\Desktop\\Doctors.xlsx");) {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
Sheet sheet1 = new Sheet(1, 0, HDoctor.class);
sheet1.setSheetName("sheet1");
writer.write(list, sheet1);
writer.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
生成结果
|