EasyPoi目前是通过适配实体类和excel表来完成对excel的上传、生成和格式化。
而主要是根据文件流或字节(符)流的方式装载和生成excel表。
EasyPoi的jar包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <dependency> <groupId>org.jeecg</groupId> <artifactId>easypoi-base</artifactId> <version>2.1.3</version> </dependency>
<dependency> <groupId>org.jeecg</groupId> <artifactId>easypoi-web</artifactId> <version>2.1.3</version> </dependency>
<dependency> <groupId>org.jeecg</groupId> <artifactId>easypoi-annotation</artifactId> <version>2.1.3</version> </dependency>
|
范例实体类
因为EasyPoi对excel的基本操作主要是通过实体类来完成,所以在最前面我把底下范例中的实体类先贴出来,方便查阅。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
@ExcelTarget("examExcel") public class ExamExcel implements java.io.Serializable {
private Long id;
@Excel(name = "教室编号", orderNum = "1") private String classroomCode;
@Excel(name = "考试地点", orderNum = "2") private String examLocation;
@Excel(name = "考场名称", orderNum = "3") private String examRoom;
@Excel(name = "场次", orderNum = "4") private String examRound;
@Excel(name = "考试日期", orderNum = "5") private String examDate;
@Excel(name = "考试时间", orderNum = "6") private String examTime;
@Excel(name = "考试课程", orderNum = "7") private String examCourse;
|
上传excel的实现
文件流实现excel的上传
1 2 3 4 5 6 7
|
public void importExamInfo(MultipartFile excel) { List<ExamExcel> examExcelList = ExcelImportUtil.importExcel(inputStream,ExamExcel.class, params); }
|
生成excel并下载的实现
getExamList(examId)
是访问数据库获取表数据的方法,这里就不贴出来了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public void exportExamExcel(long examId, HttpServletResponse response) throws IOException { response.setHeader("content-Type", "application/vnd.ms-excel"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("exam表","UTF-8") + ".xls"); List<ExamExcel> list = getExamExcelByList(getExamList(examId)); Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExamExcel.class, list); workbook.write(response.getOutputStream()); }
public List<ExamExcel> getExamExcelByList(List<Map<String, Object>> examList) { List<ExamExcel> examExcelList = new ArrayList<>(); for (Map<String, Object> examMap : examList) { ExamExcel examExcel = new ExamExcel(examMap); examExcelList.add(examExcel); } return examExcelList; }
|
对excel的格式化处理
要对excel进行美化的话这一步十分重要,但是因为EasyPoi将对excel的数据的操作进行了封装,所以我们可以在实体类中直接对数据进行格式化,而不用自己写方法。
当前版本对实体类的操作主要是通过注解来操作,例如@Excel
里面的name
代表列名,orderNum
代表列数一样,所有对数据的格式化基本都可以通过注解来完成。