当前位置: 代码迷 >> JavaScript >> Struts + JSP导出Excel表格
  详细解决方案

Struts + JSP导出Excel表格

热度:216   发布时间:2012-12-24 10:43:14.0
Struts + JSP导出Excel报表
据我所知 Java 导 Excel 报表有三种方法:
1, 在 Servlet 直接向客户端输出制表符,如下:


PrintWriter out = response.getWriter();

out.println("xxxx\t");

out.flush();
out.close();



这种方法最原始, 编起来最麻烦.

2, 利用JSP模板, 下面详述具体实现, 这种方式需要先利用office软件先生成Html模板,然后将其转化为JSP页面, 不依赖第三方实现, 比较轻量级, 适合简单应用.

3, 第三方库, jxl.jar, 这种方式最灵活,网上文章也多,不再赘述.

Struts 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
  <form-beans />
  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      path="/exportExcel"
      type="com.mypack.struts.action.ExportExcelAction"
      cancellable="true">
      <forward name="downloadPage" path="/jsp/downloadPage.jsp" />
    </action>

  </action-mappings>

  <message-resources parameter="com.mypack.struts.ApplicationResources" />
</struts-config>



Action实现:


/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.mypack.struts.action;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/** 
 * MyEclipse Struts
 * Creation date: 11-07-2010
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 */
public class ExportExcelAction extends Action {
	
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List list = new ArrayList();
		
		for (int i = 0; i < 100; i ++) {
			list.add(UUID.randomUUID().toString());
		}
		
		request.setAttribute("result", list);
		
		System.out.println(list);
		
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		//response.setHeader("Content-Disposition" ,"attachment;filename=report");
		
		response.setHeader ("Content-Disposition","attachment;filename="+ UUID.randomUUID() +".xls");
		
		return mapping.findForward("downloadPage");
	}
	
}








JSP 报表页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=Content-Type content="text/html; charset=gb2312">
<meta name=ProgId content=Excel.Sheet>
<meta name=Generator content="Microsoft Excel 11">
<link rel=File-List href="Book2.files/filelist.xml">
<link rel=Edit-Time-Data href="Book2.files/editdata.mso">
<link rel=OLE-Object-Data href="Book2.files/oledata.mso">
<!--[if gte mso 9]><xml>
 <o:DocumentProperties>
  <o:Author>微软用户</o:Author>
  <o:LastAuthor>微软用户</o:LastAuthor>
  <o:Created>2010-11-07T08:34:34Z</o:Created>
  <o:LastSaved>2010-11-07T08:38:14Z</o:LastSaved>
  <o:Company>微软中国</o:Company>
  <o:Version>11.9999</o:Version>
 </o:DocumentProperties>
</xml><![endif]-->
<style>
<!--table
	{mso-displayed-decimal-separator:"\.";
	mso-displayed-thousand-separator:"\,";}
@page
	{margin:1.0in .75in 1.0in .75in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;}
tr
	{mso-height-source:auto;
	mso-ruby-visibility:none;}
col
	{mso-width-source:auto;
	mso-ruby-visibility:none;}
br
	{mso-data-placement:same-cell;}
.style0
	{mso-number-format:General;
	text-align:general;
	vertical-align:middle;
	white-space:nowrap;
	mso-rotate:0;
	mso-background-source:auto;
	mso-pattern:auto;
	color:windowtext;
	font-size:12.0pt;
	font-weight:400;
	font-style:normal;
	text-decoration:none;
	font-family:宋体;
	mso-generic-font-family:auto;
	mso-font-charset:134;
	border:none;
	mso-protection:locked visible;
	mso-style-name:常规;
	mso-style-id:0;}
td
	{mso-style-parent:style0;
	padding-top:1px;
	padding-right:1px;
	padding-left:1px;
	mso-ignore:padding;
	color:windowtext;
	font-size:12.0pt;
	font-weight:400;
	font-style:normal;
	text-decoration:none;
	font-family:宋体;
	mso-generic-font-family:auto;
	mso-font-charset:134;
	mso-number-format:General;
	text-align:general;
	vertical-align:middle;
	border:none;
	mso-background-source:auto;
	mso-pattern:auto;
	mso-protection:locked visible;
	white-space:nowrap;
	mso-rotate:0;}
ruby
	{ruby-align:left;}
rt
	{color:windowtext;
	font-size:9.0pt;
	font-weight:400;
	font-style:normal;
	text-decoration:none;
	font-family:宋体;
	mso-generic-font-family:auto;
	mso-font-charset:134;
	mso-char-type:none;
	display:none;}
-->
</style>
<!--[if gte mso 9]><xml>
 <x:ExcelWorkbook>
  <x:ExcelWorksheets>
   <x:ExcelWorksheet>
    <x:Name>Sheet1</x:Name>
    <x:WorksheetOptions>
     <x:DefaultRowHeight>285</x:DefaultRowHeight>
     <x:Selected/>
     <x:Panes>
      <x:Pane>
       <x:Number>3</x:Number>
       <x:ActiveRow>6</x:ActiveRow>
       <x:ActiveCol>1</x:ActiveCol>
      </x:Pane>
     </x:Panes>
     <x:ProtectContents>False</x:ProtectContents>
     <x:ProtectObjects>False</x:ProtectObjects>
     <x:ProtectScenarios>False</x:ProtectScenarios>
    </x:WorksheetOptions>
   </x:ExcelWorksheet>
   <x:ExcelWorksheet>
    <x:Name>Sheet2</x:Name>
    <x:WorksheetOptions>
     <x:DefaultRowHeight>285</x:DefaultRowHeight>
     <x:ProtectContents>False</x:ProtectContents>
     <x:ProtectObjects>False</x:ProtectObjects>
     <x:ProtectScenarios>False</x:ProtectScenarios>
    </x:WorksheetOptions>
   </x:ExcelWorksheet>
   <x:ExcelWorksheet>
    <x:Name>Sheet3</x:Name>
    <x:WorksheetOptions>
     <x:DefaultRowHeight>285</x:DefaultRowHeight>
     <x:ProtectContents>False</x:ProtectContents>
     <x:ProtectObjects>False</x:ProtectObjects>
     <x:ProtectScenarios>False</x:ProtectScenarios>
    </x:WorksheetOptions>
   </x:ExcelWorksheet>
  </x:ExcelWorksheets>
  <x:WindowHeight>9585</x:WindowHeight>
  <x:WindowWidth>18195</x:WindowWidth>
  <x:WindowTopX>480</x:WindowTopX>
  <x:WindowTopY>105</x:WindowTopY>
  <x:ProtectStructure>False</x:ProtectStructure>
  <x:ProtectWindows>False</x:ProtectWindows>
 </x:ExcelWorkbook>
</xml><![endif]-->
</head>

<body link=blue vlink=purple>

<table x:str border=0 cellpadding=0 cellspacing=0 width=368 style='border-collapse:
 collapse;table-layout:fixed;width:276pt'>
 <col width=368 style='mso-width-source:userset;mso-width-alt:11776;width:276pt'>
 <tr height=19 style='height:14.25pt'>
  <td height=19 width=368 style='height:14.25pt;width:276pt'>RandomUUID</td>
 </tr>
  <c:forEach items="${result}" var="r">
 <tr height=19 style='height:14.25pt'>
  <td height=19 style='height:14.25pt'>${r}</td>
 </tr>
  </c:forEach>
 <![if supportMisalignedColumns]>
 <tr height=0 style='display:none'>
  <td width=368 style='width:276pt'></td>
 </tr>
 <![endif]>
</table>

</body>

</html>






系统下载页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="/excel/js/jquery-1.3.2.min.js"></script>
  </head>
  
  <body>
    <input id="b" type="button" value="导  出  报  表" onclick="exportExcel();">
    <a href="/excel/exportExcel.do" target="downloadf">导  出  报  表</a>
    <div id="res"></div>
    <iframe name="downloadf" style="display:none;">
    1111111111
    </iframe>
  </body>
  
  <script type="text/javascript">

		function exportExcel() {
			
			window.open("/excel/exportExcel.do","a1")   
  		    //pic.document.execCommand("SaveAs")   
   
  		    return;
  		    
			$.get("/excel/exportExcel.do", function(data) {
				alert(data);
			});
		}
	</script>
</html>





  相关解决方案