jsp导出excel的方法

原文链接:http://deific.iteye.com/blog/1088443  

        在Web应用中,很多数据经常要导出成Excel文档。通过简单的html设置就可以实现将页面数据导出为excel。

方式一: 
(1) 能够导出为excel的jsp页面中最好只保留纯数据和纯html代码。这样导出的excel格式等相对比较自然。如果有表单元素的话,导出的excel里也会是表单元素形式,如按钮等。 
(2) 在该JSP页面头部设置response的ContentType为Excel格式 

  1. <% response.setContentType("application/vnd.ms-excel;charset=GBK"); %>   

(3)页面文字为中文,但是用Excel打开为乱码则在<html>与<head>中加入 

  1. <meta http-equiv="Content-Type" content="text/html; charset=GBK">  

这样,在浏览器打开按照上述设置的页面时,会自动打开excel来读取数据。这样的设置是让浏览器以为读取到的是一个excel文件数据,会自动调用excel程序来读。 

方式二:与方式一类似,多了下载功能 。
(1) 同方式一的(1) 
(2) 在该JSP页面头部设置response的头信息 

  1. response.setHeader("Content-disposition","attachment; filename=jclxsp.xls");  

(3) 在html的head中设置相关信息 

  1. <head xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">  
  2.         <meta http-equiv="Content-Type" content="text/html; charset=GBK">  
  3.         <meta name=ProgId content=Excel.Sheet>  
  4.         <meta name=Generator content="Microsoft Excel 11">  
  5.         <link rel=File-List href="Book1.files/filelist.xml">  
  6.         <link rel=Edit-Time-Data href="Book1.files/editdata.mso">  
  7.         <link rel=OLE-Object-Data href="Book1.files/oledata.mso">  

(4) 在jsp最后,添加关闭页面代码 

  1. response.getWriter().write("<script>window.close();</script>");  

这样,在打开时,会以下载对话框,点击“保存”的话会保存为一个excel文件。点击“打开”的话,会直接用excel打开。

猜你喜欢

转载自1148499338.iteye.com/blog/2285682