下载页面信息的两种方式
js实现下载为Excel 表格
<table border="0" cellspacing="0" cellpadding="0" id="item">
<thead >
<td>姓名</td>
<td>年龄</td>
<td>生日</td>
<td>电话</td>
<td>QQ</td>
<td>学生班级</td>
<td>学生小组</td>
<td>学生就业城市</td>
<td>学生标签</td>
<c:if test="${login.role=='0'}">
<td>操作</td>
</c:if>
</thead>
<c:forEach items="${students}" var="s">
<tr>
<td>${s.name}</td>
<td>${s.age}</td>
<td><fmt:formatDate value="${s.bir}"/></td>
<td>${s.tel}</td>
<td>${s.qq}</td>
<td>${s.clazz.name}</td>
<td>${s.team.name}</td>
<td>${s.city.name}</td>
<td><c:forEach items="${s.tag}" var="t">${t.name} </c:forEach></td>
<c:if test="${login.role=='0'}">
<td><a href="${pageContext.request.contextPath }/student/findOne?&id=${s.id}">详细</a>|<a href="${pageContext.request.contextPath }/student/remove?&id=${s.id}">删除</a>|<a href="${pageContext.request.contextPath }/student/beforeUpdate?&id=${s.id}">修改</a></td>
</c:if>
</tr>
</c:forEach>
</table>
<hr/>
<script type="text/javascript">
function base64 (content) {
return window.btoa(unescape(encodeURIComponent(content)));
}
function tableToExcel(tableID,fileName){
var table = document.getElementById(tableID);
var excelContent = table.innerHTML;
var excelFile = "<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'>";
excelFile += "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>";
excelFile += "<body><table>";
excelFile += excelContent;
excelFile += "</table></body>";
excelFile += "</html>";
var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
var a = document.createElement("a");
a.download = fileName+".xls";
a.href = link;
a.click();
}
</script>
<a href="" id="a1" onclick="tableToExcel('item','学生信息表')">导出学生信息</a>
后台java代码实现信息的下载
public void exportStudentInfo() throws IOException {
List<Student> studentList = studentService.queryAll();
StringBuilder sb = new StringBuilder();
studentList.forEach(s->{
sb.append(s.toString());
sb.append("\n");
});
ByteArrayInputStream bis = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("学生信息.txt","UTF-8"));
ServletOutputStream ots = response.getOutputStream();
IOUtils.copy(bis,ots);
IOUtils.closeQuietly(bis);
IOUtils.closeQuietly(ots);
}