在项目中,有时会出现需要将数据库数据导出报表等功能,这时一般会用到poi库。poi是一个专门给Java程序提供格式文档读写功能的API接口,包括各种微软的格式文档入excel、word等。最常用的还是Excel格式导入导出。
Easypoi是在poi接口基础上进行了封装,简化了操作。
使用Easypoi导出仅需以下几步:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
Easypoi注解包含下面几类
示例:
public class StudentEntity implements java.io.Serializable {
/**
* id
*/
@ExcelIgnore
private String id;
/**
* 学生姓名
*/
@Excel(name = "学生姓名", height = 20, width = 30, isImportField = "true_st")
private String name;
/**
* 学生性别
*/
@Excel(name = "学生性别", replace = { "男_1", "女_2" }, suffix = "生", isImportField = "true_st")
private int sex;
@Excel(name = "出生日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd", isImportField = "true_st", width = 20)
private Date birthday;
@Excel(name = "进校日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd")
private Date registrationDate;
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生","学生"),
StudentEntity .class, list);
workbook.setSheetName(0, fileName);
workbook.getSheetAt(0).setDefaultRowHeight((short)21);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String savePath = Constants.EXCEL_FILE_PREFIX + fileName + sdf.format(new Date()) + ".xls";
String accessPath = fileAccessUrlPrefix + savePath;
try {
File filePath = new File(localPathPrefix + BosConstants.EXCEL_FILE_PREFIX);
if (!filePath.exists()) {
filePath.mkdirs();
}
File localFile = new File(localPathPrefix + File.separator + savePath);
OutputStream os = new FileOutputStream(localFile);
workbook.write(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
参考:EasyPos教程