好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java 如何快速,优雅的实现导出Excel

前言:

春节假期刚刚过去,大家是不是已经开始了搬砖生活啦,嘻嘻 o(∩_∩)o ,可我还在休假中呢 !

好啦,咱们言归正传,开始聊聊正文。做过后端管理系统的同学,大概率都会收到过实现 导出 Excel 的功能需求,因为这个功能在后台管理系统中是个必备功能。

那大家是怎么实现这个功能的呢?

使用Apache提供POI组件实现; 使用现成的、简便的第三方工具库(避免重复造轮子)

Hutool 工具库中的Excel工具类
EasyExcel 阿里开源的基于 Java 的简单、省内存的读写Excel工具库

接下来咱们来聊聊使用 Hutool、EasyExcel 工具库实现导出Excel。

使用第三方库实现导出Excel

业界有句话:不重复造轮子。 使用工具类可以减少日常繁琐的编码,减少重复的编码时间,提高开发效率。 作为程序员,应该多善于利用工具减少代码冗余,美化自己的代码。

使用 Hutool 工具库实现导出Excel:

1、首先添加依赖
在pom.xml中添加上依赖:

<!--hutool 导出 Excel 工具组件--> <dependency>    <groupId> cn.hutool </groupId>    <artifactId> hutool-all </artifactId>    <version> 5.1.0 </version> </dependency>   <!--POI组件--> <dependency>    <groupId> org.apache.poi </groupId>    <artifactId> poi-ooxml </artifactId>    <version> 4.1.0 </version> </dependency>

上面除了引入了 hutool 依赖之外,还引入了 poi-ooxml 依赖,这个包会自动关联引入poi包,且可以很好的支持Office2007+的文档格式 。

2、然后使用工具类实现导出Excel

import  cn . hutool . core . collection . CollUtil ; import  cn . hutool . poi . excel . ExcelUtil ; import  cn . hutool . poi . excel . ExcelWriter ; import  cn . hutool . poi . excel . StyleSet ; import  org . apache . poi . ss . usermodel . CellStyle ; import  org . apache . poi . ss . usermodel . Font ;   import  java . util . ArrayList ; import  java . util . Date ; import  java . util . LinkedHashMap ; import  java . util . List ; import  java . util . Map ;   /**  * @PACKAGE_NAME: com.lyl.excel  * @ClassName: HutoolExcelUtils  * @Description: 使用 Hutool 中的工具类实现 Excel的导出  * @Date: 2021-02-18 16:24  * @Author: [木子雷] 公众号  **/ public   class   HutoolExcelUtils   {        /**      * 导出Excel      *      * @param args      */      public   static   void  main ( String []  args )   {            ArrayList < Map < String ,   Object >>  rows  =   CollUtil . newArrayList ( data ());          ExcelWriter  writer  =   null ;            try   {              String  path  =   "E:/QQPCmgr/Desktop/" ;                String  excelName  =   "Hutool"   +   System . currentTimeMillis ()   +   ".xlsx" ;              // 通过工具类创建writer,固定的文件输出路径             writer  =   ExcelUtil . getWriter ( path  +  excelName );                // 定义第一行合并单元格样式              CellStyle  headCellStyle  =  writer . getHeadCellStyle ();              // 设置内容字体              Font  font  =  writer . createFont ();              // 字体加粗             font . setBold ( true );              // 字体颜色             font . setColor ( Font . COLOR_RED );             headCellStyle . setFont ( font );                // 设置第 0 列的单元格的宽度,列数从零开始计算             writer . setColumnWidth ( 0 ,   20 );             writer . setColumnWidth ( 1 ,   20 );             writer . setColumnWidth ( 2 ,   20 );                // 定义数据行的样式              StyleSet  style  =  writer . getStyleSet ();              // 设置单元格文本内容自动换行             style . setWrapText ();                // 合并单元格后的标题行(第一行),使用默认标题样式             writer . merge ( rows . get ( 0 ). size ()   -   1 ,   "导出测试:TEST" );              // 一次性写出内容,使用默认样式,强制输出标题             writer . write ( rows ,   true );            }   catch   ( Exception  e )   {             e . printStackTrace ();          }   finally   {              if   ( writer  !=   null )   {                  // 记住关闭 writer,释放内存                 writer . close ();              }          }      }        /**      * 构造 导出的数据      *      * @return      */      public   static   List < Map < String ,   Object >>  data ()   {          // 导出的数据          ArrayList < Map < String ,   Object >>  rows  =   new   ArrayList <>();            for   ( int  i  =   0 ;  i  <   10 ;  i ++)   {              Map < String ,   Object >  row  =   new   LinkedHashMap <>();               row . put ( "字符串标题" ,   "字符串"   +  i );             row . put ( "日期标题" ,   new   Date ());             row . put ( "数字标题" ,   0.56 );             rows . add ( row );          }          return  rows ;      }   }

注意:

记得修改代码中导出Excel的路径 path 导出Excel的样式是可以灵活变化的,可以自行进行设置

3、导出Excel的样式如下

4、注意事项

在导出大数据量时,可能会出现内存溢出的问题,不要担心,Hutool也为我们提供了 BigExcelWriter 来避免大数据量输出时可能会出现的内存溢出问题。 上面的例子中,只实现了部分的样式设置,Hutool还提供了许多其它的样式,大家可以自行去尝试;并且 Hutool 也支持写出到 Web客户端下载 。

官方文档地址: Hutool 操作 Excel

使用 EasyExcel 工具库实现导出Excel:

EasyExcel是一个基于Java的简单、省内存的读写Excel的 阿里开源 项目;正如它在GitHub中项目代码介绍的那样:一个快速、简单避免OOM的java处理Excel工具。

测试得知 64M内存1分钟内读取75M(46W行25列)的Excel ;除此之外还有 急速模式 能更快,但是内存占用会在100M多一点 。

1、首先添加依赖

<!--  阿里开源的 excel 工具类库 --> <dependency>    <groupId> com.alibaba </groupId>    <artifactId> easyexcel </artifactId>    <version> 2.2.6 </version> </dependency>

注意: 此依赖不能和 poi-ooxml 依赖在一起用,否则运行时会报 类找不到 的异常。

2、然后使用工具类实现导出Excel
①、导出的数据模版类:

import  com . alibaba . excel . annotation . ExcelIgnore ; import  com . alibaba . excel . annotation . ExcelProperty ; import  com . alibaba . excel . annotation . write . style . ColumnWidth ; import  com . alibaba . excel . annotation . write . style . ContentFontStyle ; import  com . alibaba . excel . annotation . write . style . ContentRowHeight ; import  com . alibaba . excel . annotation . write . style . ContentStyle ; import  com . alibaba . excel . annotation . write . style . HeadFontStyle ; import  com . alibaba . excel . annotation . write . style . HeadRowHeight ; import  com . alibaba . excel . annotation . write . style . HeadStyle ; import  org . apache . poi . ss . usermodel . FillPatternType ;   import  java . util . Date ;   /**  * @PACKAGE_NAME: com.lyl.excel  * @ClassName: DemoData  * @Description:  使用 EasyExcel 导出数据时的数据模版  * @Date: 2021-01-27 17:46  * @Author: [木子雷] 公众号  **/   // 标题行 背景设置成红色 IndexedColors.RED.getIndex() @HeadStyle ( fillPatternType  =   FillPatternType . SOLID_FOREGROUND ,  fillForegroundColor  =   10 ) // 标题行 字体设置成20 @HeadFontStyle ( fontHeightInPoints  =   20 ) @ContentRowHeight ( 25 ) // 文本内容行的高度 @HeadRowHeight ( 30 ) // 标题行的高度 @ColumnWidth ( 20 ) // 全局的列宽 public   class   DemoData   {        // 字符串的列内容 背景设置成天蓝 IndexedColors.SKY_BLUE.getIndex()      @ContentStyle ( fillPatternType  =   FillPatternType . SOLID_FOREGROUND ,  fillForegroundColor  =   40 )      // 字符串的列内容 字体设置成20      @ContentFontStyle ( fontHeightInPoints  =   20 )      @ExcelProperty ({ "导出测试:TEST" ,   "字符串标题" })      private   String   string ;        @ColumnWidth ( 30 )      @ExcelProperty ({ "导出测试:TEST" ,   "日期标题" })      private   Date  date ;        @ExcelProperty ({ "导出测试:TEST" ,   "数字标题" })      private   Double  doubleData ;        /**      * 忽略这个字段      */      @ExcelIgnore      private   String  ignore ;        public   String  getString ()   {          return   string ;      }        public   void  setString ( String   string )   {          this . string   =   string ;      }        public   Date  getDate ()   {          return  date ;      }        public   void  setDate ( Date  date )   {          this . date  =  date ;      }        public   Double  getDoubleData ()   {          return  doubleData ;      }        public   void  setDoubleData ( Double  doubleData )   {          this . doubleData  =  doubleData ;      }        public   String  getIgnore ()   {          return  ignore ;      }        public   void  setIgnore ( String  ignore )   {          this . ignore  =  ignore ;      } }

注意: 这个数据模版类中使用了大量的 自定义注解 ,通过使用注解可以使代码变得更加的优雅、简洁 。

关于项目中自定义注解的实际使用可以参考: 自定义注解的魅力你到底懂不懂

②、实现数据导出到Excel:

import  com . alibaba . excel . EasyExcel ;   import  java . util . ArrayList ; import  java . util . Date ; import  java . util . List ;   /**  * @PACKAGE_NAME: com.lyl.excel  * @ClassName: EasyExcelUtils  * @Description: 阿里巴巴 开源的  easyexcel 工具  * @Date: 2021-01-20 16:58  * @Author: [木子雷] 公众号  **/ public   class   EasyExcelUtils   {        public   static   void  main ( String []  args )   {          // 导出Excel的路径          String  path  =   "E:/QQPCmgr/Desktop/" ;            // 导出Excel路径 + 文件名称          String  filename  =  path  +   "EasyExcel"   +   System . currentTimeMillis ()   +   ".xlsx" ;            /**          * 导出excel          * filename:导出excel全路径          * DemoData.class:导出excel时的 数据模版          * 模板:指的是导出excel的sheet页          * data():构造的DemoData.class数据模版的数据集合           */          EasyExcel . write ( filename ,   DemoData . class ). sheet ( "模板" ). doWrite ( data ());      }        /**      * 构造 导出的数据      *      * @return      */      private   static   List < DemoData >  data ()   {          List < DemoData >  list  =   new   ArrayList < DemoData >();          for   ( int  i  =   0 ;  i  <   10 ;  i ++)   {              DemoData  data  =   new   DemoData ();             data . setString ( "字符串"   +  i );             data . setDate ( new   Date ());             data . setDoubleData ( 0.56 );             list . add ( data );          }          return  list ;      } }

注意:

记得修改代码中导出Excel的路径 path

导出Excel的样式是可以灵活变化的,可以自行进行设置

3、导出Excel的样式如下

4、EasyExcel 导出Excel扩展:

上面导出Excel的例子中,只实现了其中一部分功能,还有很多功能由于篇幅原因没法一一展示出来,在这就简单说下支持的其它功能:

通过设置 只导出模版数据中的指定列数据 通过设置 将模版数据中的列数据导出到Excel中指定的列上 可以将导出的数据分多个批次导入到同一个Excel中,避免大数据量时的内存溢出问题 导出数据的自定义格式转换,例如:日志、数字的格式转换等 支持将图片导出到Excel中 支持根据已有的Excel模版样式 将数据导出Excel 支持单元格合并、表格方式导出、自动列宽、设置单元格下拉、超链接等、以及插入批注 除了上面的导出Excel功能之外,EasyExcel还支持 读取Excel数据、Web客户端的上传、下载等 ;

官方文档地址: 阿里开源 EasyExcel

项目代码地址: alibaba/easyexcel

EasyExcel项目代码拉取下来后,可以直接去单元测试包下,查看已提供的功能测试使用方法:

以上就是Java 如何快速,优雅的实现导出Excel的详细内容,更多关于Java 实现导出Excel的资料请关注其它相关文章!

原文链接:https://leishen6.github.io/2021/02/19/exportExcel/

查看更多关于Java 如何快速,优雅的实现导出Excel的详细内容...

  阅读:27次