【在线教育】EasyExcel入门(二)

简介: EasyExcel入门

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*/@Data@ContentRowHeight(20)
@HeadRowHeight(20)  //行高@ColumnWidth(25)    //列宽publicclassStudent2 {
@ExcelProperty("编号")
privateStringid;
@ExcelProperty({"基本信息","姓名"})   //复制表头privateStringname;
@ExcelProperty({"基本信息","年龄"})
privateIntegerage;
@ExcelProperty("电话")
privateStringtelephone;
@ExcelProperty("邮箱")
privateStringemail;
@ExcelProperty("生日")
@DateTimeFormat("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;
    }
@TestpublicvoidtestMoreSheetWrite(){
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();
        }
    }
}
读操作@TestpublicvoidtestMoreRead(){
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 写操作:多对象


Student@Data@NoArgsConstructor@AllArgsConstructorpublicclassStudent {
@ExcelProperty("姓名")
privateStringname;
@ExcelProperty("年龄")
privateIntegerage;
}
Book@Data@NoArgsConstructor@AllArgsConstructor@HeadRowHeight(50)
@HeadFontStyle(fontName="黑体",italic=BooleanEnum.TRUE, color=Font.COLOR_RED, underline=2)
publicclassBook {
@ExcelProperty("编号")
privateStringid;
@ExcelProperty({"作者信息","姓名"})
privateStringauthorName;
@ExcelProperty({"作者信息","年龄"})
privateIntegerauthorAge;
@ExcelProperty({"书籍基本信息","标题"})
privateStringtitle;
@ContentFontStyle(fontName="楷书",italic=BooleanEnum.TRUE, color=Font.COLOR_RED, underline=-1)
@ExcelProperty({"书籍基本信息","价格"})
privateDoubleprice;
@ExcelProperty({"书籍基本信息","出版日期"})
@DateTimeFormat("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;
    }
@TestpublicvoidtestManyObject() {
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备份数据库


image.png

  • 步骤
  • 步骤1:添加坐标
  • 步骤2:编写封装类
  • 步骤3:编写核心类

image.png

步骤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;
/*** 课程**/@Data@ContentRowHeight(20)
@HeadRowHeight(20)  //行高@ColumnWidth(25)    //列宽publicclassChapter {
@ExcelProperty("章节ID")
privateStringid;
@ExcelProperty("课程ID")
privateStringcourseId;
@ExcelProperty("章节名称")
privateStringtitle;
@ExcelProperty("显示排序")
privateIntegersort;
@ExcelProperty("创建时间")
privateDategmtCreate;
@ExcelProperty("更新时间")
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;
/*** 课程**/@Data@ContentRowHeight(20)
@HeadRowHeight(20)  //行高@ColumnWidth(25)    //列宽publicclassCourse {
@ExcelProperty("课程ID")
privateStringid;
@ExcelProperty("课程讲师ID")
privateStringteacherId;
@ExcelProperty("课程专业ID二级分类ID")
privateStringsubjectId;
@ExcelProperty("一级分类ID")
privateStringsubjectParentId;
@ExcelProperty("课程标题")
privateStringtitle;
@ExcelProperty("课程销售价格,设置为0则可免费观看")
privateDoubleprice;
@ExcelProperty("总课时")
privateIntegerlessonNum;
@ExcelProperty("课程封面图片路径")
privateStringcover;
@ExcelProperty("销售数量")
privateLongbuyCount;
@ExcelProperty("浏览数量")
privateLongviewCount;
@ExcelProperty("乐观锁")
privateLongversion;
@ExcelProperty("视频状态 Draft未发布  Normal已发布")
privateStringstatus;
@ExcelProperty("创建时间")
@DateTimeFormat("yyyy年MM月dd日")
privateDategmtCreate;
@ExcelProperty("更新时间")
@DateTimeFormat("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);
        }
    }
@TestpublicvoidtestDB() 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();
    }
}


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
9月前
|
人工智能 Java 网络安全
|
Docker 容器
容器的日志
【10月更文挑战第31天】
1440 68
|
存储 关系型数据库 MySQL
美团面试:MySQL为什么 不用 Docker部署?
45岁老架构师尼恩在读者交流群中分享了关于“MySQL为什么不推荐使用Docker部署”的深入分析。通过系统化的梳理,尼恩帮助读者理解为何大型MySQL数据库通常不使用Docker部署,主要涉及性能、管理复杂度和稳定性等方面的考量。文章详细解释了有状态容器的特点、Docker的资源隔离问题以及磁盘IO性能损耗,并提供了小型MySQL使用Docker的最佳实践。此外,尼恩还介绍了Share Nothing架构的优势及其应用场景,强调了配置管理和数据持久化的挑战。最后,尼恩建议读者参考《尼恩Java面试宝典PDF》以提升技术能力,更好地应对面试中的难题。
|
网络协议 数据处理
说一说 Netty 中的心跳机制
我是小假 期待与你的下一次相遇 ~
275 1
|
Java 文件存储 Spring
轻松实现Spring Boot与FastDFS的无缝整合
家人们啦!,上篇文章了,我们讲了如何使用docker-compose快速部署fastdfs,在今天的文章中,我将向大家介绍如何将Spring Boot与FastDFS进行无缝整合,以便高效地管理和操作文件存储。通过这个整合,你将能够轻松地在Spring Boot应用程序中实现文件的上传和下载等功能。让我们开始吧
1070 0
轻松实现Spring Boot与FastDFS的无缝整合
Exception in thread "main" java.lang.IllegalArgumentException: U+6570 ('.notdef') is not available in the font Helvetica-Bold, encoding: WinAnsiEncoding 问题解决
【5月更文挑战第26天】Exception in thread "main" java.lang.IllegalArgumentException: U+6570 ('.notdef') is not available in the font Helvetica-Bold, encoding: WinAnsiEncoding 问题解决
1323 2
|
传感器 数据安全/隐私保护 数据格式
STM32CubeMX DHT11温湿度传感器
STM32CubeMX DHT11温湿度传感器
2205 12
|
SpringCloudAlibaba Java Maven
【问题篇】Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/
【问题篇】Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/
687 2
|
存储 分布式计算 大数据
大数据技术概述
大数据技术概述
|
移动开发 前端开发 Java
Flowable 任务监听器与执行监听器的介绍
Flowable 任务监听器与执行监听器的介绍
4420 1