在网络上有很多关于jsp页面导出为excel表格的例子,但好多是需要前台与后台相互关联实现的,我在这里的实例是只需要在jsp页面写代码即可实现,代码如下:
testexcel.jsp页面代码:
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<script type="text/javascript">
function exportexcel(){
window.open('testexcel.jsp?exporttoexcel=yes');
}
</script>
<head>
<!-- 显示网格线 -->
<xml>
<x:excelworkbook>
<x:excelworksheets>
<x:excelworksheet>
<x:name>工作表标题</x:name>
<x:worksheetoptions>
<x:print>
<x:validprinterinfo />
</x:print>
</x:worksheetoptions>
</x:excelworksheet>
</x:excelworksheets>
</x:excelworkbook>
</xml>
<!-- 显示网格线 -->
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>export to excel - demo</title>
</head>
<body>
<%
string exporttoexcel = request.getparameter("exporttoexcel");
if (exporttoexcel != null
&& exporttoexcel.tostring().equalsignorecase("yes")) {
response.setcontenttype("application/vnd.ms-excel");
response.setheader("content-disposition", "inline; filename="
+ "excel.xls");
}
%>
<table align="left" border="2">
<thead>
<tr bgcolor="lightgreen">
<th>id</th>
<th>文本内容</th>
<th>序列</th>
<td style="display: none">序列222</td>
</tr>
</thead>
<tbody>
<%
for (int i = 0; i < 10; i++) {
%>
<tr bgcolor="lightblue">
<td align="center"><%=i%></td>
<td align="center">文本内容 <%=i%></td>
<td align="center"><%=i*10%></td>
<td style="display: none" align="center"><%=i * 20%></td>
</tr>
<%
}
%>
</tbody>
</table>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<%
if (exporttoexcel == null) {
%>
<a href="javascript:exportexcel();">导出为excel</a>
<%
}
%>
</body>
</html>
ps:当你点击“导出到excel”超链接的时候,所有页面的内容会被导出excel中。但是,我们可能不想让“导出到excel”的超链接出现在excel中。为了阻止它的出现,我们增加了一个判断条件,判断exporttoexcel参数是否出现。如果出现,就意味着内容会被导出到excel中,而且不包括超链接。反之,就意味着我们只是想浏览器显示网页,那么超链接会出现在页面上。
以上就是jsp 导出excel表格实例详解的详细内容。