在Web应用中,很多数据经常要导出成Excel文档。用专门的生成真正的Excel文档的方式比较复杂,不太好用。所以经常用一种简单的方式来实现,即将报表保存为HTML格式,然后用Excel打开。 实现方式: 第一步,用JSP实现HTML版本的报表 第二步,在该JSP页面头部设置response的ContentType为Excel格式 <% response.setContentType("application/vnd.ms-excel;charset=GBK"); %> 中文问题: 查看源代码时发现JSP文件中写死的中文为乱码,则在JSP文件头部添加一行 <%@ page contentType="text/html; charset=gb2312" %> 查看源代码时发现文字为中文,但是用Excel打开为乱码则在<html>与<head>中加入 <meta http-equiv="Content-Type" content="text/html; charset=GBK"> 用Servlet实现也是类似的处理方法。
实现样例:
- <%@ page contentType="text/html; charset=UTF-8" %>
<% response.setContentType("application/vnd.ms-excel;charset=UTF-8"); %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<table cellpadding="1" cellspacing="1" border="1">
<tr>
<td colspan="5" align="center">
${ticketname}
</td>
</tr>
<tr class="dan_tr">
<th>使用时间</th>
<th>使用者</th>
<th>传播者</th>
<th>使用地点</th>
<th>消耗积分</th>
</tr>
<c:forEach var="list" items="${list}">
<tr align="center">
<td width="135">${list.userDate}</td>
<td width="100">${list.userName}</td>
<td width="100">${list.puserName}</td>
<td width="350">${list.userCorp}</td>
<td>${list.integral}分</td>
</tr>
</c:forEach>
</table>
</body>