当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot快速集成jxls-poi(自定义模板,支持本地文件导出,在线文件导出)

SpringBoot快速集成jxls-poi(自定义模板,支持本地文件导出,在线文件导出)

2020年09月07日  | 移动技术网IT编程  | 我要评论
在项目持续集成的过程中,有时候需要实现报表导出和文档导出,类似于excel中这种文档的导出,在要求不高的情况下,有人可能会考虑直接导出csv文件来简化导出过程。但是导出xlsx文件,其实过程相对更复杂

在项目持续集成的过程中,有时候需要实现报表导出和文档导出,类似于excel中这种文档的导出,在要求不高的情况下,有人可能会考虑直接导出csv文件来简化导出过程。但是导出xlsx文件,其实过程相对更复杂。解决方案就是使用poi的jar包。使用源生的poi来操作表格,代码冗余,处理复杂,同时poi的相关联的依赖还会存在版本兼容问题。所以直接使用poi来实现表格导出,维护成本大,不易于拓展。

我们需要学会站在巨人的肩膀上解决问题,jxls-poi这个就很好解决这个excel表格导出的多样化的问题。类似jsp和thymealf的模板定义,使得表格导出变得简单可控。

不多bb上代码

1.引入关键依赖包

<!-- jxls-api依赖 -->
		<dependency>
			<groupid>org.jxls</groupid>
			<artifactid>jxls-poi</artifactid>
			<version>1.0.15</version>
		</dependency>

		<dependency>
			<groupid>org.jxls</groupid>
			<artifactid>jxls</artifactid>
			<version>2.4.6</version>
		</dependency>

这里只需要两个依赖便操作excel表格了。

2.定义模板文件


新建一个excel文件,后缀名为.xlsx,在resources目录下新增一个jxls的文件夹,把模板文件放在这个文件夹下,便于后续的spring-boot的集成。

3.导出工具类

/**
 * @author machenike
 */
public class excelutils {

  /***
   * excel导出到response
   * @param filename   导出文件名
   * @param templatefile 模板文件地址
   * @param params     数据集合
   * @param response   response
   */
  public static void exportexcel(string filename, inputstream templatefile, map<string, object> params,
                  httpservletresponse response) throws ioexception {
    response.reset();
    response.setheader("accept-ranges", "bytes");
    outputstream os = null;
    response.setheader("content-disposition", string.format("attachment; filename=\"%s\"", filename));
    response.setcontenttype("application/octet-stream;charset=utf-8");
    try {
      os = response.getoutputstream();
      exportexcel(templatefile, params, os);
    } catch (ioexception e) {
      throw e;
    }
  }

  /**
   * 导出excel到输出流中
   * @param templatefile 模板文件
   * @param params 传入参数
   * @param os 输出流
   * @throws ioexception
   */
  public static void exportexcel(inputstream templatefile, map<string, object> params, outputstream os) throws ioexception {
    try {
      context context = new context();
      set<string> keyset = params.keyset();
      for (string key : keyset) {
        //设置参数变量
        context.putvar(key, params.get(key));
      }
      map<string, object> myfunction = new hashmap<>();
      myfunction.put("fun", new excelutils());
      // 启动新的jxls-api 加载自定义方法
      transformer trans = transformerfactory.createtransformer(templatefile, os);
      jexlexpressionevaluator evaluator = (jexlexpressionevaluator) trans.gettransformationconfig().getexpressionevaluator();
      evaluator.getjexlengine().setfunctions(myfunction);

      // 载入模板、处理导出
      areabuilder areabuilder = new xlscommentareabuilder(trans);
      list<area> arealist = areabuilder.build();
      arealist.get(0).applyat(new cellref("sheet1!a1"), context);
      trans.write();
    } catch (ioexception e) {
      throw e;
    } finally {
      try {
        if (os != null) {
          os.flush();
          os.close();
        }
        if (templatefile != null) {
          templatefile.close();
        }
      } catch (ioexception e) {
        throw e;
      }
    }
  }

  /**
   * 格式化时间
   */
  public object formatdate(date date) {
    if (date != null) {
      simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
      string datestr = sdf.format(date);
      return datestr;
    }
    return "--";
  }


  /**
   * 设置超链接方法
   */
  public writablecellvalue getlink(string address, string title) {
    return new writablehyperlink(address, title);
  }
}

这个工具类中我定义两个导出用的方法
一个是直接是httpservletresponse 导出在线下载文件
一个使用输入流导出
同时模板中还支持方法传入。

4.定义导出服务类

全局配置jxls模板的基础路径

#jxls模板的基础路径
jxls.template.path: classpath:jxls/

定义服务接口

/**
 * excel用service
 */
public interface excelservice {

  /**
   * 导出excel,写入输出流中
   * @param templatefile
   * @param params
   * @param os
   * @return
   */
  boolean getexcel(string templatefile,map<string,object> params, outputstream os);

  /**
   * 导出excel,写入response中
   * @param templatefile
   * @param filename
   * @param params
   * @param response
   * @return
   */
  boolean getexcel(string templatefile,string filename, map<string,object> params, httpservletresponse response);

  /**
   * 导出excel,写入文件中
   * @param templatefile
   * @param params
   * @param outputfile
   * @return
   */
  boolean getexcel(string templatefile, map<string,object> params, file outputfile);
}

excel导出用服务实现类

/**
 * excel用serviceimpl
 */
@service
public class excelserviceimppl implements excelservice {

  private static final logger logger = loggerfactory.getlogger(excelserviceimppl.class);

  /**
   * 模板文件的基础路径
   */
  @value("${jxls.template.path}")
  private string templatepath;

  @override
  public boolean getexcel(string templatefile, map<string, object> params, outputstream os) {
    fileinputstream inputstream = null;
    try {
      //获取模板文件的输入流
      inputstream = new fileinputstream(resourceutils.getfile(templatepath + templatefile));
      //导出文件到输出流
      excelutils.exportexcel(inputstream, params, os);
    } catch (ioexception e) {
      logger.error("excel export has error" + e);
      return false;
    }
    return true;
  }

  @override
  public boolean getexcel(string templatefile, string filename, map<string, object> params, httpservletresponse response) {
    fileinputstream inputstream = null;
    try {
      //获取模板文件的输入流
      inputstream = new fileinputstream(resourceutils.getfile(templatepath + templatefile));
      //导出文件到response
      excelutils.exportexcel(filename,inputstream,params,response);
    } catch (ioexception e) {
      logger.error("excel export has error" + e);
      return false;
    }
    return true;
  }

  @override
  public boolean getexcel(string templatefile, map<string, object> params, file outputfile) {
    fileinputstream inputstream = null;
    try {
      //获取模板文件的输入流
      inputstream = new fileinputstream(resourceutils.getfile(templatepath + templatefile));
      file dfile = outputfile.getparentfile();
      //文件夹不存在时创建文件夹
      if(dfile.isdirectory()){
        if(!dfile.exists()){
          dfile.mkdir();
        }
      }
      //文件不存在时创建文件
      if(!outputfile.exists()){
        outputfile.createnewfile();
      }
      //导出excel文件
      excelutils.exportexcel(inputstream, params, new fileoutputstream(outputfile));
    } catch (ioexception e) {
      logger.error("excel export has error" + e);
      return false;
    }
    return true;
  }
}

如上,服务类提供了,三种导出的实现方法

  • 导出excel写入response中
  • 导出excel写入输出流中
  • 导出excel写入文件中

这三种方法足以覆盖所有的业务需求

5.编辑jxls模板

这里为方便导出最好定义与模板匹配的实体类,便于数据的装载和导出

public class usermodel {

  private integer id;

  private string name;

  private string sex;

  private integer age;

  private string remark;

  private date date;

  private string link;
  }


插入标注定义模板,定义迭代对象jx:each

jx:each(items="list" var="item" lastcell="g3")

上面g3 模板中迭代的结束位置,然后用类似el表达式的方式填充到模板当中


填写范围jx:area

jx:area(lastcell="g3")

模板编辑完成后保存即可,

6.代码测试使用

导出为本地文件

@springboottest
class blogjxlsapplicationtests {

  @autowired
  excelservice excelservice;

  @test
  void contextloads() {
    map<string, object> params = new hashmap();
    list<usermodel> list = new arraylist<>();
    list.add(new usermodel(1, "test01", "男", 25, "tttttttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(2, "test02", "男", 20, "tttttttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(3, "test04", "女", 25, "ttttddddasdadatttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(4, "test08", "男", 20, "ttttttdasdatttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(5, "test021", "女", 25, "ttttdatttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(7, "test041", "男", 25, "ttdadatttttttt",new date(),"htpp://wwww.baidu.com"));

		params.put("list", list);
    excelservice.getexcel("t1.xlsx", params, new file("d:\\test05.xlsx"));
  }
}

导出成功

在线导出文件

@restcontroller
public class testcontroller {
  @autowired
  excelservice excelservice;

  @requestmapping("test")
  public void testfile(httpservletresponse response){
    map<string, object> params = new hashmap();
    list<usermodel> list = new arraylist<>();
    list.add(new usermodel(1, "test01", "男", 25, "tttttttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(2, "test02", "男", 20, "tttttttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(3, "test04", "女", 25, "ttttddddasdadatttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(4, "test08", "男", 20, "ttttttdasdatttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(5, "test021", "女", 25, "ttttdatttttt",new date(),"htpp://wwww.baidu.com"));
    list.add(new usermodel(7, "test041", "男", 25, "ttdadatttttttt",new date(),"htpp://wwww.baidu.com"));

    params.put("list", list);
    excelservice.getexcel("t1.xlsx",system.currenttimemillis()+".xlsx", params,response);
  }
}


导出成功


源码地址
https://github.com/davidlei08/blogjxls.git

到此这篇关于springboot快速集成jxls-poi(自定义模板,支持本地文件导出,在线文件导出)的文章就介绍到这了,更多相关springboot集成jxls-poi内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网