当前位置: 移动技术网 > IT编程>开发语言>Java > SpringMvc导出Excel实例代码

SpringMvc导出Excel实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

前言

相信很多朋友在实际工作中都会要将数据导出成excel的需求,通常这样的做法有两种。

一是采用jxl来生成excel,之后保存到服务器,然后在生成页面之后下载该文件。

二是使用poi来生成excel,之后使用stream的方式输出到前台直接下载(ps:当然也可以生成到服务器中再下载。)。这里我们讨论第二种。

struts2的方式

通常我会将已经生成好的hssfworkbook放到一个inputstream中,然后再到xml配置文件中将返回结果更改为stream的方式。如下:

private void responsedata(hssfworkbook wb) throws ioexception {
  bytearrayoutputstream baos = new bytearrayoutputstream();
  wb.write(baos);
  baos.flush();
  byte[] aa = baos.tobytearray();
  excelstream = new bytearrayinputstream(aa, 0, aa.length);
  baos.close();
}

配置文件:

<action name="exportxxx" class="xxxaction" method="exportxxx">
  <result name="exportsuccess" type="stream">
    <param name="inputname">excelstream</param>
    <param name="contenttype">application/vnd.ms-excel</param>
    <param name="contentdisposition">attachment;filename="undefined.xls"</param>
  </result>
</action>

这样即可达到点击链接即可直接下载文件的目的。

springmvc的方式

先贴代码:

@requestmapping("/exportxxx.action")
public void exportxxx(httpservletrequest request, httpservletresponse response,
    @requestparam(value="scheduleid", defaultvalue="0")int scheduleid){
  hssfworkbook wb = createexcel(scheduleid) ;
  try {
    response.setheader("content-disposition", "attachment; filename=appointmentuser.xls");
    response.setcontenttype("application/vnd.ms-excel; charset=utf-8") ;
    outputstream out = response.getoutputstream() ;
    wb.write(out) ;
    out.flush();
    out.close();
  } catch (ioexception e) {
    e.printstacktrace();
  } 
}

其实springmvc和struts2的原理上是一样的,只是struts2是才去配置文件的方式。首先是使用createexcel()这个方法来生成excel并返回,最后利用response即可向前台输出excel,这种方法是通用的,也可以试用与servlet、struts2等。我们只需要在response的头信息中设置相应的输出信息即可。

总结

不管是使用struts2,还是使用springmvc究其根本都是使用的response,所以只要我们把response理解透了不管是下载图片、world、excel还是其他什么文件都是一样的。

github地址:https://github.com/crossoverjie

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网