JSP导出到excel,word

来源:互联网 发布:java爬虫书籍推荐2016 编辑:程序博客网 时间:2024/05/16 16:58

Excel:

Java代码 复制代码 收藏代码
  1. <%   
  2.     response.setHeader("Content-disposition","inline; filename=test.xls");   
  3. //让前端浏览器以为接收到一个excel档 ,并设定传送到前端浏览器时的档名为test.xls  
  4.   
  5. 或者:   
  6.     response.setHeader("Content-disposition","attachment; filename=test.xls");   
  7. //attachment是以附件下载的形式,inline是以线上浏览的形式。当点击“保存”的时候都可以下载,当点击“打开”的时候attachment是在Excel里打开,inline是在浏览器里打开。  
  8. %>   
  9. 头部加入:<%@ page contentType="application/msexcel; charset=gb2312" %>    //不是必须,不加貌似也可以……  

word:
Java代码 复制代码 收藏代码
  1. <%   
  2.     response.setHeader("Content-disposition","inline; filename=test.doc");   
  3. 或者:   
  4.     response.setHeader("Content-disposition","attachment; filename=test.doc");   
  5. %>   
  6. 头部加入:word为<%@ page contentType="application/vnd.ms-word; charset=gb2312" %>    
//不是必须,不加貌似也可以……

注意的是,导出的文件命名用中文出错,对word排版最好用div,用table即使border=0在word上还是有虚框出来。


demo(直接在ie运行就可以):


Jsp代码 复制代码 收藏代码
  1. <%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>   
  2. <%   
  3. String fileName = "最简单的导出表格.xls";   
  4. fileName = new String(fileName.getBytes("GBK"),"ISO8859_1");   
  5. response.setHeader("Content-Disposition",    
  6.    "attachment;filename="+fileName);   
  7.       
  8. response.setDateHeader("Expires"0);    
  9. response.setHeader("Cache-Control""no-cache");    
  10. response.setHeader("Pragma""no-cache");   
  11. %>   
  12. <HTML>   
  13. <HEAD>   
  14. <META http-equiv="Content-Type" content="text/html; charset=utf-8" />   
  15. <meta content="">   
  16. <TITLE>最简单的导出表格</TITLE>   
  17. </HEAD>   
  18. <BODY>   
  19. <TABLE >   
  20.   <TBODY>   
  21.     <TR >   
  22.       <TH nowrap="nowrap" style="TEXT-ALIGN: center" >代理商ID</TH>   
  23.       <TH nowrap="nowrap" style="TEXT-ALIGN: center" >代理商名称</TH>   
  24.       <TH nowrap="nowrap" style="TEXT-ALIGN: center" >联系手机</TH>   
  25.     </TR>   
  26.      <TR height="30">      
  27.       <TD align="center" nowrap="nowrap"> July</TD>   
  28.       <TD align="center" nowrap="nowrap"> 男</TD>   
  29.       <TD align="center" nowrap="nowrap"> 羽毛球</TD>   
  30.          
  31.     </TR>   
  32.      <TR height="30">      
  33.       <TD align="center" nowrap="nowrap"> July</TD>   
  34.       <TD align="center" nowrap="nowrap"> 男</TD>   
  35.       <TD align="center" nowrap="nowrap"> 羽毛球</TD>   
  36.          
  37.     </TR>   
  38.      <TR height="30">      
  39.       <TD align="center" nowrap="nowrap"> July</TD>   
  40.       <TD align="center" nowrap="nowrap"> 男</TD>   
  41.       <TD align="center" nowrap="nowrap"> 羽毛球</TD>   
  42.          
  43.     </TR>   
  44.   </TBODY>   
  45. </TABLE>   
  46. </BODY>   
  47. </HTML>