1.5 复杂操作
1.5.1 复合表头
packagecom.czxy.zx.demo02; importcom.alibaba.excel.annotation.ExcelProperty; importcom.alibaba.excel.annotation.format.DateTimeFormat; importcom.alibaba.excel.annotation.write.style.ColumnWidth; importcom.alibaba.excel.annotation.write.style.ContentRowHeight; importcom.alibaba.excel.annotation.write.style.HeadRowHeight; importlombok.Data; importjava.util.Date; /*** @author 桐叔* @email liangtong@itcast.cn*/20) (20) //行高 (25) //列宽 (publicclassStudent2 { "编号") (privateStringid; "基本信息","姓名"}) //复制表头 ({privateStringname; "基本信息","年龄"}) ({privateIntegerage; "电话") (privateStringtelephone; "邮箱") (privateStringemail; "生日") ("yyyy年MM月dd日") (privateDatebrithday; }
1.5.2 写操作:多表
packagecom.czxy.zx.demo02; importcom.alibaba.excel.EasyExcel; importcom.alibaba.excel.ExcelWriter; importcom.alibaba.excel.write.metadata.WriteSheet; importcom.czxy.zx.demo01.Student; importorg.junit.Test; importjava.util.ArrayList; importjava.util.Date; importjava.util.List; /*** @author 桐叔* @email liangtong@itcast.cn*/publicclassTestExcel2 { /*** 获得根路径* @return*/publicStringgetPath() { returnthis.getClass().getResource("/").getPath(); } /*** 准备数据* @return*/privateList<Student2>getData(Integerflag){ List<Student2>list=newArrayList<Student2>(); for(intm=0 ; m<10 ; m++){ Stringi=""+flag+m ; Student2student=newStudent2(); student.setId("stu"+i); student.setName("wang"+i); student.setAge( 18 ); student.setTelephone("1361234"+i); student.setEmail("wang"+i+"@czxy.com"); student.setBrithday(newDate()); list.add(student); } returnlist; } publicvoidtestMoreSheetWrite(){ Stringfile=getPath() +"student_demo2.xls"; ExcelWriterexcelWriter=EasyExcel.write(file).build(); for (inti=0; i<5; i++) { WriteSheetwriteSheet=EasyExcel.writerSheet(i, "模板"+i).head(Student2.class).build(); // 分页去数据库查询数据 这里可以去数据库查询每一页的数据List<Student2>data=getData(i); excelWriter.write(data, writeSheet); } excelWriter.finish(); } }
1.5.3 读操作:多表
- 具有缓存处理类
packagecom.czxy.zx.demo02; importcom.alibaba.excel.context.AnalysisContext; importcom.alibaba.excel.event.AnalysisEventListener; importjava.util.ArrayList; importjava.util.List; /*** Created by liangtong.*/publicclassStudent2ListenerextendsAnalysisEventListener<Student2> { // 批量操作数privatestaticfinalintBATCH_COUNT=10; // 用于缓存信息privateList<Student2>cache=newArrayList<Student2>(); publicvoidinvoke(Student2student, AnalysisContextanalysisContext) { //保存学生信息cache.add(student); if(cache.size() >=BATCH_COUNT){ // 保存数据saveData(); } } publicvoiddoAfterAllAnalysed(AnalysisContextanalysisContext) { //最后的不够 BATCH_COUNT 倍数saveData(); } privatevoidsaveData() { // 集合不为空if(!cache.isEmpty()) { // 处理缓存数据System.out.println(cache); // 清空缓存cache.clear(); } } } 读操作publicvoidtestMoreRead(){ Stringfile=getPath() +"student_demo2.xls"; //EasyExcel.read(文件, 封装对象, 处理类).sheet("表").doRead();ExcelReaderexcelReader=EasyExcel.read(file, Student2.class, newStudent2Listener()).build(); // 确定需要解析的sheetfor (inti=0; i<5; i++) { ReadSheetreadSheet=EasyExcel.readSheet("模板"+i).build(); excelReader.read(readSheet); } excelReader.finish(); }
1.6.4 写操作:多对象
StudentpublicclassStudent { "姓名") (privateStringname; "年龄") (privateIntegerage; } Book50) (fontName="黑体",italic=BooleanEnum.TRUE, color=Font.COLOR_RED, underline=2) (publicclassBook { "编号") (privateStringid; "作者信息","姓名"}) ({privateStringauthorName; "作者信息","年龄"}) ({privateIntegerauthorAge; "书籍基本信息","标题"}) ({privateStringtitle; fontName="楷书",italic=BooleanEnum.TRUE, color=Font.COLOR_RED, underline=-1) ("书籍基本信息","价格"}) ({privateDoubleprice; "书籍基本信息","出版日期"}) ({"yyyy年MM月dd日") (privateDatepublishDate; } 实现packagecom.czxy.zx.demo03; importcom.alibaba.excel.EasyExcel; importcom.alibaba.excel.ExcelWriter; importcom.alibaba.excel.write.metadata.WriteSheet; importcom.czxy.zx.demo01.Student; importcom.czxy.zx.demo02.Book; importorg.junit.Test; importjava.util.*; /*** @author 桐叔* @email liangtong@itcast.cn*/publicclassTestManyObject { // 获得当前项目的运行时的根目录publicStringgetPath() { returnthis.getClass().getResource("/").getPath(); } // 模拟数据publicList<Student>getStudentData() { List<Student>list=newArrayList<>(); for (inti=0; i<20; i++) { list.add(newStudent("张三"+i, 18+i)); } returnlist; } publicList<Book>getBookData() { List<Book>list=newArrayList<>(); for (inti=0; i<20; i++) { list.add(newBook(i+"" , "张三"+i , 18+i, "坏蛋是怎么"+i, 998d+i, newDate())); } returnlist; } // 遍历map即可privateMap<Class<?>, List<?>>getData() { Map<Class<?>, List<?>>map=newHashMap<>(); map.put(Student.class, getStudentData()); map.put(Book.class, getBookData()); returnmap; } publicvoidtestManyObject() { Stringfile=getPath() +"many_object.xlsx"; //1 开始写ExcelWriterexcelWriter=EasyExcel.write(file).build(); //2 依次写每一个对象for(Map.Entry<Class<?>, List<?>>entry : getData().entrySet()) { Class<?>clazz=entry.getKey(); //类型List<?>data=entry.getValue(); //数据WriteSheetwriteSheet=EasyExcel.writerSheet(clazz.getSimpleName()).head(clazz).build(); excelWriter.write(data, writeSheet); } //3 写完成excelWriter.finish(); } }
1.6 扩展:excel备份数据库
- 步骤
- 步骤1:添加坐标
- 步骤2:编写封装类
- 步骤3:编写核心类
步骤1:添加坐标<dependencies><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.7</version></dependency></dependencies>步骤2:编写封装类packagecom.czxy.zx.demo03; importcom.alibaba.excel.annotation.ExcelProperty; importcom.alibaba.excel.annotation.write.style.ColumnWidth; importcom.alibaba.excel.annotation.write.style.ContentRowHeight; importcom.alibaba.excel.annotation.write.style.HeadRowHeight; importlombok.Data; importjava.util.Date; importjava.util.List; /*** 课程**/20) (20) //行高 (25) //列宽 (publicclassChapter { "章节ID") (privateStringid; "课程ID") (privateStringcourseId; "章节名称") (privateStringtitle; "显示排序") (privateIntegersort; "创建时间") (privateDategmtCreate; "更新时间") (privateDategmtModified; } packagecom.czxy.zx.demo03; importcom.alibaba.excel.annotation.ExcelProperty; importcom.alibaba.excel.annotation.format.DateTimeFormat; importcom.alibaba.excel.annotation.write.style.ColumnWidth; importcom.alibaba.excel.annotation.write.style.ContentRowHeight; importcom.alibaba.excel.annotation.write.style.HeadRowHeight; importlombok.Data; importjava.util.Date; /*** 课程**/20) (20) //行高 (25) //列宽 (publicclassCourse { "课程ID") (privateStringid; "课程讲师ID") (privateStringteacherId; "课程专业ID二级分类ID") (privateStringsubjectId; "一级分类ID") (privateStringsubjectParentId; "课程标题") (privateStringtitle; "课程销售价格,设置为0则可免费观看") (privateDoubleprice; "总课时") (privateIntegerlessonNum; "课程封面图片路径") (privateStringcover; "销售数量") (privateLongbuyCount; "浏览数量") (privateLongviewCount; "乐观锁") (privateLongversion; "视频状态 Draft未发布 Normal已发布") (privateStringstatus; "创建时间") ("yyyy年MM月dd日") (privateDategmtCreate; "更新时间") ("yyyy年MM月dd日") (privateDategmtModified; } 步骤3:编写核心类packagecom.czxy.zx.demo03; importcom.alibaba.excel.EasyExcel; importcom.alibaba.excel.ExcelWriter; importcom.alibaba.excel.write.metadata.WriteSheet; importcom.czxy.zx.demo02.Student2; importorg.apache.commons.dbutils.BasicRowProcessor; importorg.apache.commons.dbutils.DbUtils; importorg.apache.commons.dbutils.GenerousBeanProcessor; importorg.apache.commons.dbutils.QueryRunner; importorg.apache.commons.dbutils.handlers.BeanListHandler; importorg.junit.Test; importjava.sql.*; importjava.util.*; /*** @author 桐叔* @email liangtong@itcast.cn*/publicclassTestBackdb { publicClassgetClassByTableName(StringtableName) { Map<String,Class>map=newHashMap<>(); map.put("edu_chapter", Chapter.class); map.put("edu_course", Course.class); returnmap.get(tableName); } publicStringgetPath() { returnthis.getClass().getResource("/").getPath(); } publicConnectiongetConnection() { try { Class.forName("com.mysql.jdbc.Driver"); Stringurl="jdbc:mysql://127.0.0.1:3306/zx_edu_course?useUnicode=true&characterEncoding=utf8"; Stringusername="root"; Stringpassword="1234"; Propertiesprops=newProperties(); props.setProperty("user", username); props.setProperty("password", password); props.setProperty("remarks", "true"); //设置可以获取remarks信息props.setProperty("useInformationSchema", "true"); //设置可以获取tables remarks信息returnDriverManager.getConnection(url, props); } catch (Exceptione) { thrownewRuntimeException(e); } } publicvoidtestDB() throwsException { Stringfile=getPath() +"db.xls"; QueryRunnerqueryRunner=newQueryRunner(); ExcelWriterexcelWriter=EasyExcel.write(file).build(); StringdbName="zx_edu_course"; //获得连接Connectionconn=getConnection(); //语句执行者Statementst=conn.createStatement(); //数据库的元数据DatabaseMetaDatadatabaseMetaData=conn.getMetaData(); //获得所有的数据库ResultSetcatalogResultSet=databaseMetaData.getCatalogs(); //遍历所有的数据库while(catalogResultSet.next()) { //获得数据库的名称StringdatabaseName=catalogResultSet.getString(1); if(dbName.equals(databaseName)) { //使用数据库st.execute("use "+databaseName); ResultSettableResultSet=databaseMetaData.getTables(databaseName, null, null, null); //遍历所有的表名while(tableResultSet.next()) { //表名StringtableName=tableResultSet.getString(3); //TABLE_NAMEStringtableRemarks=tableResultSet.getString("REMARKS"); //获得表的备注// 通过表名获得excel处理类ClassexcelBeanClass=getClassByTableName(tableName); if(excelBeanClass!=null) { //获得当前表的所有数据Stringsql="select * from "+tableName; //Listdata= (List) queryRunner.query(conn, sql, newBeanListHandler<>(excelBeanClass, newBasicRowProcessor(newGenerousBeanProcessor()) )); // 创建sheetWriteSheetwriteSheet=EasyExcel.writerSheet(tableRemarks!=null?tableRemarks : tableName).head(excelBeanClass).build(); excelWriter.write(data, writeSheet); } } } } //写入完成excelWriter.finish(); } }