javaweb导出excel

jsp页面:

1 <form id="dataForm" action="exportCost/expTable.htm" method="post" style="display:none">
2                 <input id="startDate_h" name="startDate_h" type="text"  />  <!-- 传数据  -->
3                 <input id="endDate_h" name="endDate_h" type="text" />
4                 <input id="dissort_h" name="dissort_h" type="text"/>
5             </form>
<button id="export_excel">导出excel</button>

js代码:

$('#export_excel').click(function(){
            $("#dataForm")[0].submit(); 
        });

java后台处理代码:

 1 @RequestMapping(value = "/expToExcel", method = RequestMethod.POST)
 2     public void expToExcel(HttpServletRequest request, HttpServletResponse response)throws Exception {
 3         PrintWriter pw=response.getWriter();
 4         try{
 5             response.setContentType("application/x-msdownload;charset=gbk");
 6             response.setCharacterEncoding("UTF-8");
 7             String fileName =  "" + ".xls";
 8             String fileNameTemp = URLEncoder.encode(fileName, "UTF-8");
 9             response.setHeader("Content-Disposition", "attachment; filename="
10                     + new String(fileNameTemp.getBytes("utf-8"), "gbk"));
11             OutputStream os = response.getOutputStream();
12             //ExcelUtils eu = new ExcelUtils();
13             //eu.export(os, "",  legends ,colLength, DbUtils.ListMapToListObject(result),0,0);
14             os.flush();
15             os.close();
16         }catch(Exception e){
17             e.printStackTrace();
18             pw.print("fail");
19         }
20     }

上面的关键代码是: 

1 OutputStream os = response.getOutputStream();
2             response.setContentType("application/x-msdownload;charset=gbk");
3             response.setCharacterEncoding("UTF-8");
4             response.setHeader("Content-Disposition", "attachment; filename="+ "");
5             os.flush();
6             os.close();
对response对象进行设置,然后获取到OutputStream 对象,对这个对象 进行操作,然后就可以导出了。
这里我们用的是jxl导出excel。
<dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>

参考文章:http://www.cnblogs.com/forlina/archive/2011/06/15/2081153.html

原文地址:https://www.cnblogs.com/lishupeng/p/5590290.html