只需要在jsp文件头上设置,其关键代码如下:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
response.setHeader("Pragma ", "public");
response.setHeader("Cache-Control ", "must-revalidate, post-check=0, pre-check=0 ");
response.addHeader("Cache-Control ", "public ");
response.addHeader("Content-Disposition", "attachment; filename=user.xls");
response.setContentType("application/vnd.ms-excel.numberformat:@;charset=UTF-8");
%>
<html>
注意添加相关依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10.1</version>
</dependency>
其整个jsp文件如下:
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
response.setHeader("Pragma ", "public");
response.setHeader("Cache-Control ", "must-revalidate, post-check=0, pre-check=0 ");
response.addHeader("Cache-Control ", "public ");
response.addHeader("Content-Disposition", "attachment; filename=user.xls");
response.setContentType("application/vnd.ms-excel.numberformat:@;charset=UTF-8");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="charset=utf-8" />
<style>
table {
border: thin solid #333;
border-collapse: collapse;
border-spacing: 0px;
}
th {
background-color: #ccc;
border: thin solid #333;
}
td {
border: thin solid #000;
}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="1" align="center" class="global_tableresult" style="width: 100%">
<tr>
<th width="8%">姓名</th>
<th width="8%">年龄</th>
<th width="8%">工作</th>
<th width="5%">地址</th>
<th width="10%">电话</th>
</tr>
<c:forEach items="${ulist}" var="user">
<tr>
<td>${user.name }</td>
<td>${user.age}</td>
<td>${user.job }</td>
<td>${user.addr}</td>
<td>${user.tel }</td>
</tr>
</c:forEach>
</table>
</body>
</html>