欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot内存数据导出成Excel的实现方法

程序员文章站 2022-07-03 19:11:12
前言这是本人写的一个springboot对excel写入的方法,实测能用,待提升的地方有很多,有不足之处请多多指点。excel2003版(后缀为.xls)最大行数是65536行,最大列数是256列。e...

前言

这是本人写的一个springboot对excel写入的方法,实测能用,待提升的地方有很多,有不足之处请多多指点。

excel2003版(后缀为.xls)最大行数是65536行,最大列数是256列。

excel2007以上的版本(后缀为.xlsx)最大行数是1048576行,最大列数是16384列。

若数据量超出行数,需要进行脚页的控制,这一点没做,因为一般100w行已够用。

提供3种方法写入:

1.根据给定的实体类列list和列名数组arr[]进行excel写入

2.根据给定的list和key的顺序数组key[]进行excel写入

3.根据给定的list按顺序excel写入,列名数组arr[]需要自行和数据列顺序进行一一对应

同名的excel会被覆盖!!!

写入excel所需要的几个类

SpringBoot内存数据导出成Excel的实现方法

1.在pom.xml加上依赖

</dependencies>
 <dependency>
  <groupid>org.apache.poi</groupid>
  <artifactid>poi</artifactid>
  <version>4.0.1</version>
 </dependency>
 <dependency>
  <groupid>org.apache.poi</groupid>
  <artifactid>poi-ooxml</artifactid>
  <version>4.0.1</version>
 </dependency>
</dependencies>

2.excelpojo实体类

package com.cly.utils.excel;

/**
 * @author : cly
 * @classname : excelpojo
 * @date : 2020/7/9 17:13
 * 实体类所有成员变量都需要有get,set方法
 * 所有成员变量都要加上注解@excelrescoure(value = "?"),?为excel真实列名,必须一一对应
 * @excelrescoure(value = "?"),?可为空,需要用到才赋值
 * 成员变量目前只允许string,double,interge,float
 **/

public class excelpojo {
 public string getname() {
 return name;
 }
 public void setname(string name) {
 this.name = name;
 }
 public string getpasswork() {
 return passwork;
 }
 public void setpasswork(string passwork) {
 this.passwork = passwork;
 }
 public string getlook() {
 return look;
 }
 public void setlook(string look) {
 this.look = look;
 }
 
 @excelrescoure(value = "姓名")
 private string name;
 @excelrescoure(value = "密码")
 private string passwork;
 @excelrescoure(value = "工号")
 private string look;
 
 @override
 public string tostring(){
 return "name:"+this.getname()+",passwork:"+this.getpasswork()+",look:"+this.getlook();
 }
 public excelpojo() {}
}

3.@interface自定义注解(用于实体类读取)

package com.cly.utils.excel;

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

/**
 * @author : cly
 * @classname : myrescoure
 * @date : 2020/7/10 9:31
 **/
@target(elementtype.field)
@retention(retentionpolicy.runtime)
public @interface excelrescoure {
 string value() default "";//默认为空
}

4.excelwrite类(写入excel数据类)有很多冗余的代码,可抽离出来

package com.cly.utils.excel;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.xssfcellstyle;
import org.apache.poi.xssf.usermodel.xssfworkbook;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import javax.servlet.http.httpservletresponse;
import java.beans.introspectionexception;
import java.beans.propertydescriptor;
import java.io.*;
import java.lang.reflect.field;
import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.net.urlencoder;
import java.text.simpledateformat;
import java.util.*;

/**
 * @author : cly
 * @classname : excelwrite
 * @date : 2020/7/17 17:01
 **/
public class excelwrite {
 //日志输出
 private static logger logger = loggerfactory.getlogger(excelwrite.class);

 /**
 * 方法一:
 * 实体类数据写入新建的excel
 * @path:excel文件路径
 * @array[]:文件首行数据列名,可为空,为空时不存在首行列名
 * @list<t>:实体类数据数列
 */
 public static <t> string writetoexcelbypojo(string path, string[] array, list<t> list) {
 /* for (t t : list) {
  system.out.println(t);
 }*/
 //创建工作薄
 workbook wb = new xssfworkbook();
 /**标题和页码*/
 cellstyle titlestyle = wb.createcellstyle();
 // 设置单元格对齐方式
 titlestyle.setalignment(horizontalalignment.center); // 水平居中
 //titlestyle.setverticalalignment(); // 默认垂直居中
 // 设置字体样式
 font titlefont = wb.createfont();
 titlefont.setfontheightinpoints((short) 12); // 字体高度
 titlefont.setfontname("黑体"); // 字体样式
 titlestyle.setfont(titlefont);
 //创建sheet
 sheet sheet = wb.createsheet("第一页");
 sheet.autosizecolumn(0);// 自动设置宽度
 // 在sheet中添加标题行
 row row = sheet.createrow((int) 0);// 行数从0开始
 for (int i = 0; i < array.length; i++) {
  cell cell = row.createcell(i);
  cell.setcellvalue(array[i]);
  cell.setcellstyle(titlestyle);
 }
 /**数据样式*/
 // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
 cellstyle datastyle = wb.createcellstyle();
 // 设置居中样式
 datastyle.setalignment(horizontalalignment.center); // 水平居中

 /**处理实体类数据并写入*/
 //获取当前的泛型对象
 object obj = list.get(0);
 arraylist arraylist = new arraylist();
 //linkedhashmap保证顺序
 linkedhashmap<string, object> pojofields = getpojofieldandvalue(obj);
 for (int i = 0; i < array.length; i++) {
  for (map.entry<string, object> map : pojofields.entryset()) {
  if (map.getkey().equals(array[i])) {
   arraylist.add(map.getvalue());
  }
  }
 }
 if (array.length != arraylist.size()) {
  return "标题列数和实体类标记数不相同";
 }
 try {
  //数据从序号1开始
  int index = 1;
  //利用迭代器,遍历集合数据,产生数据行
  iterator<t> it = list.iterator();
  while (it.hasnext()) {
  row = sheet.createrow(index);// 默认的行数从0开始,为了统一格式设置从1开始,就是从excel的第二行开始
  index++;
  t t = (t) it.next();
  //system.out.println("t:" + t);
  for (int i = 0; i < arraylist.size(); i++) {
   string fieldname = (string) arraylist.get(i);
   //system.out.println(fieldname);
   string getmethodname = "get" + fieldname.substring(0, 1).touppercase() + fieldname.substring(1);
   //system.out.println(getmethodname);
   class<? extends object> tcls = t.getclass();// 泛型为object以及所有object的子类
   //system.out.println(tcls);
   method method = tcls.getmethod(getmethodname, new class[]{});// 通过方法名得到对应的方法
   //propertydescriptor pd = new propertydescriptor((string) arraylist.get(i), it.getclass());
   //获取成员变量的get方法
   //method method = pd.getwritemethod();
   object value = method.invoke(t, new object[]{});// 动态调用方,得到属性值
   //system.out.println(value.tostring());
   cell cell = row.createcell(i);
   if (value != null) {
   if (value instanceof date) {
    simpledateformat simpledateformat = new simpledateformat("yyyy-mm-dd");
    value = simpledateformat.format(value);
   }
   cell.setcellvalue(value.tostring());// 为当前列赋值
   cell.setcellstyle(datastyle);//设置数据的样式
   }
  }
  }
  fileoutputstream fileout = new fileoutputstream(path);
  wb.write(fileout);
  fileout.flush();
  wb.close();
  fileout.close();
  return "success";
 } catch (exception e) {
  e.printstacktrace();
 }
 return "faile";
 }


 /**
 * 获取对应的实体类成员
 */
 private static linkedhashmap<string, object> getpojofieldandvalue(object t) {
 //声明返回结果集
 linkedhashmap<string, object> result = new linkedhashmap<>();
 field[] fields = t.getclass().getdeclaredfields();//获取属性名
 if (fields != null) {
  for (field field : fields) {
  excelrescoure rescoure = field.getannotation(excelrescoure.class);
  if (rescoure.value() != null && !"".equals(rescoure.value())) {
   result.put(rescoure.value(), field.getname());
  }
  }
 } else {
  logger.warn("实体类:" + t + "不存在成员变量");
  return null;
 }
 return result;
 }

 /**---------------------===================================================---------------------------**/

 /**
 * 方法2:
 * hashmap数据写入新建的excel
 * @path:excel文件路径
 * @array[]:文件首行数据列名,可为空,为空时不存在首行列名
 * @list<map<?,?>>:hashmap数据数列
 * @key:hashmap里面的key值,需要一一对应列名的顺序
 * */
 public static string writetoexcelbyhashmap (string path, string[] array, list<hashmap> list,string[] key){
 //创建工作薄
 workbook wb = new xssfworkbook();
 /**标题和页码*/
 cellstyle titlestyle = wb.createcellstyle();
 // 设置单元格对齐方式
 titlestyle.setalignment(horizontalalignment.center); // 水平居中
 //titlestyle.setverticalalignment(); // 默认垂直居中
 // 设置字体样式
 font titlefont = wb.createfont();
 titlefont.setfontheightinpoints((short) 12); // 字体高度
 titlefont.setfontname("黑体"); // 字体样式
 titlestyle.setfont(titlefont);
 //创建sheet
 sheet sheet = wb.createsheet("第一页");
 sheet.autosizecolumn(0);// 自动设置宽度
 // 在sheet中添加标题行
 row row = sheet.createrow((int) 0);// 行数从0开始
 for (int i = 0; i < array.length; i++) {
  cell cell = row.createcell(i);
  cell.setcellvalue(array[i]);
  cell.setcellstyle(titlestyle);
 }
 /**数据样式*/
 // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
 cellstyle datastyle = wb.createcellstyle();
 // 设置居中样式
 datastyle.setalignment(horizontalalignment.center); // 水平居中

 /**数据写入*/
 //数据从序号1开始
 try {
  int index = 1;
  for (int i = 0; i < list.size(); i++) {
  row = sheet.createrow(index);// 默认的行数从0开始,为了统一格式设置从1开始,就是从excel的第二行开始
  index++;
  hashmap hashmap= list.get(i);
  for (int j = 0; j < key.length; j++) {
   cell cell = row.createcell(j);
   cell.setcellvalue(hashmap.get(key[j]).tostring());// 为当前列赋值
   cell.setcellstyle(datastyle);//设置数据的样式
  }
  }
  fileoutputstream fileout = new fileoutputstream(path);
  wb.write(fileout);
  fileout.flush();
  wb.close();
  fileout.close();
  return "success";
 }catch (exception e){
  e.printstacktrace();
 }
 return "faile";
 }

 /**------------------===========================================================------------------------------------------------------*/
 /**
 * 方法3:
 * hashmap数据写入新建的excel
 * @path:excel文件路径
 * @array[]:文件首行数据列名,可为空,为空时不存在首行列名,列名需要和数列的数据顺序一一对应
 * @list<list>:数列数据数列
 *
 * */
 public static string writetoexcelbylist(string path, string[] array, list<list> list){
  //创建工作薄
  workbook wb = new xssfworkbook();
  /**标题和页码*/
  cellstyle titlestyle = wb.createcellstyle();
  // 设置单元格对齐方式
  titlestyle.setalignment(horizontalalignment.center); // 水平居中
  //titlestyle.setverticalalignment(); // 默认垂直居中
  // 设置字体样式
  font titlefont = wb.createfont();
  titlefont.setfontheightinpoints((short) 12); // 字体高度
  titlefont.setfontname("黑体"); // 字体样式
  titlestyle.setfont(titlefont);
  //创建sheet
  sheet sheet = wb.createsheet("第一页");
  sheet.autosizecolumn(0);// 自动设置宽度
  // 在sheet中添加标题行
  row row = sheet.createrow((int) 0);// 行数从0开始
  for (int i = 0; i < array.length; i++) {
  cell cell = row.createcell(i);
  cell.setcellvalue(array[i]);
  cell.setcellstyle(titlestyle);
  }
  /**数据样式*/
  // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
  cellstyle datastyle = wb.createcellstyle();
  // 设置居中样式
  datastyle.setalignment(horizontalalignment.center); // 水平居中

  /**数据写入*/
  //数据从序号1开始
  try {
  int index = 1;
  for (int i = 0; i < list.size(); i++) {
   row = sheet.createrow(index);// 默认的行数从0开始,为了统一格式设置从1开始,就是从excel的第二行开始
   index++;
   list data= list.get(i);
   for (int j = 0; j < data.size(); j++) {
   cell cell = row.createcell(j);
   cell.setcellvalue(data.get(j).tostring());// 为当前列赋值
   cell.setcellstyle(datastyle);//设置数据的样式
   }
  }
  fileoutputstream fileout = new fileoutputstream(path);
  wb.write(fileout);
  fileout.flush();
  wb.close();
  fileout.close();
  return "success";
  }catch (exception e){
  e.printstacktrace();
  }
  return "faile";
 }
}

5.测试类,同名的excel会被覆盖

package com.cly.utils.excel;


import java.util.*;

/**
 * @author : cly
 * @classname : writetest
 * @date : 2020/7/31 15:26
 **/
public class writetest {
 public static void main(string[] args) throws exception {
 /**实体类测试
 * writetoexcelbypojo(string path, string[] array, list<t> list)
 * @path:excel文件路径
 * @array[]:文件首行数据列名,可为空,为空时不存在首行列名
 * @list<t>:实体类数据数列
 * 注意同名的excel会被覆盖,请写好文件名字和对应的后缀
 */
 excelpojo excelpojo = new excelpojo();
 excelpojo.setname("name");
 excelpojo.setpasswork("pass");
 excelpojo.setlook("look");
 excelpojo pojo2 = new excelpojo();
 pojo2.setname("name2");
 pojo2.setpasswork("pass2");
 pojo2.setlook("look2");
 excelpojo pojo3 = new excelpojo();
 pojo3.setname("name3");
 pojo3.setpasswork("pass3");
 pojo3.setlook("look3");
 list<excelpojo> list = new arraylist<>();
 list.add(excelpojo);
 list.add(pojo2);
 list.add(pojo3);
 /**列名对应实体类中成员变量@excelrescoure的值,只需要写入要的列明,不必全部成员变量都写上*/
 string[] arr = {"姓名", "密码"};
 string s = excelwrite.writetoexcelbypojo("d:\\123.xls", arr, list);
 system.out.println(s);

 /**hashmap测试
 * writetoexcelbyhashmap (string path, string[] array, list<hashmap> list,string[] key)
 * @path:excel文件路径
 * @array[]:文件首行数据列名,可为空,为空时不存在首行列名
 * @list<map<?,?>>:hashmap数据数列
 * @key:hashmap里面的key值,需要一一对应列名的顺序
 * 注意同名的excel会被覆盖,请写好文件名字和对应的后缀
 */
 hashmap hashmap= new hashmap<>();
 hashmap.put("1","q");
 hashmap.put("0","w");
 hashmap.put("5","e");
 hashmap.put("2","r");
 hashmap hashmap2= new hashmap<>();
 hashmap2.put("1","q2");
 hashmap2.put("0","w2");
 hashmap2.put("5","e2");
 hashmap2.put("2","r2");
 /**列名顺序*/
 string[] arr2 = {"第一列","第二列","第三列","第四列"};
 /**hashmap中的数据key对应列名顺序,不存在列名或顺序要求可随意,但该数组数据必须要*/
 string[] key = {"0","1","2","5"};
 list list = new arraylist();
 list.add(hashmap);
 list.add(hashmap2);
 string s = excelwrite.writetoexcelbyhashmap("d:\\123.xls", arr2, list,key);
 system.out.println(s);

 /**list测试
 * writetoexcelbylist(string path, string[] array, list<list> list)
 * @path:excel文件路径
 * @array[]:文件首行数据列名,可为空,为空时不存在首行列名,列名需要和数列的数据顺序一一对应
 * @list<list>:数列数据数列
 * 注意同名的excel会被覆盖,请写好文件名字和对应的后缀
 */
 string[] arr3 = {"第一列","第二列","第三列","第四列"};
 list data = new arraylist();
 data.add("1");
 data.add("2");
 data.add("3");
 data.add("4");
 list data2 = new arraylist();
 data2.add("5");
 data2.add("6");
 data2.add("7");
 data2.add("8");
 list<list> list1 = new arraylist();
 list1.add(data);
 list1.add(data2);
 string s = excelwrite.writetoexcelbylist("d:\\123.xls", arr3, list1);
 system.out.println(s);
 }
}

6.运行结果和说明

1.实体类测试结果

SpringBoot内存数据导出成Excel的实现方法
SpringBoot内存数据导出成Excel的实现方法

2.hashmap测试

SpringBoot内存数据导出成Excel的实现方法

3.list测试

SpringBoot内存数据导出成Excel的实现方法

还有很多不足的地方,请多多指点,希望能给你带来帮助。

springboot实现excel读取在另一篇文章 文章地址:

总结

到此这篇关于springboot内存数据导出成excel的文章就介绍到这了,更多相关springboot内存数据导出成excel内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!