公司的一个项目用到了前端导出Excel,可以把页面Table中的数据和格式一并导出,非常方便,在这边做个记录。
有几个关键点需要注意:
- Response设置:
- ContentType:application/vnd.ms-excel ---设置文件类型
- Content-Disposition:attachment;fileName=excel.xls ---设置文件名
- Style样式:
- 尽量不要使用引入的CSS文件中的样式,否则,导出的excel文件用WPS或者office打开不带样式
代碼如下:
<%@ 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 + "/";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;fileName=\"" + "mainmaterialdown.xls" + "\"");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'mainmaterialdown.jsp' starting page</title>
<style type="text/css">
body {
margin: 10px 0 0 10px;
padding: 0px;
}
h3 {
margin: -8px 0px 0px 20px;
}
.table td, tr {
border: 1px solid #CCE1E3;
height: 30px;
}
tr.titletr td {
background: #f8f0d0;
height: 28px;
color: #000000;
font-size: 12px;
}
.table {
width: 100%;
font-size: 13px;
text-align: center;
float: left;
border: 1px solid #CCE1E3;
border-collapse: collapse;
}
</style>
</head>
<body>
<form method="post">
<table class="table">
<tr align="center">
<td colspan="4"><h3>主料件制程基礎資料導出數據</h3></td>
</tr>
<tr class="titletr">
<td>法人</td>
<td>製造處名稱</td>
<td>廠部名稱</td>
<td>主料件制程</td>
</tr>
<c:if test="${mainMaterialDTOs.size()>0}">
<c:forEach var="item" items="${mainMaterialDTOs}" varStatus="status">
<tr>
<td>${item.artificialPerson}</td>
<td style="border-left:0;border-top:0;">${item.parentDepartName}</td>
<td style="border-left:0;border-top:0;">${item.departName}</td>
<td style="border-left:0;border-top:0;">${item.materialsAndParts}</td>
</tr>
</c:forEach>
</c:if>
<c:if test="${empty mainMaterialDTOs}">
<tr>
<td colspan="8">
無記錄
</td>
</tr>
</c:if>
</table>
</form>
</body>
</html>
来源:oschina
链接:https://my.oschina.net/u/3748342/blog/4469293