在写一个 SSM 项目的时候需要添加 excel 数据导出的功能, 实质上也就是将从数据库中渲染到前端的数据保存为一个 excel 的形式并下载。
xlsx.js 是由 SheetJS 出品的js-xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多,支持 xls、xlsx、ods等十几种格式。附链接 Github 打包下载取库内的 js 文件即可。
dist > xlsx.core.min.js
导入 js
<script src="../js/xlsx.core.min.js"></script>
引自
如果需要使用的话, 注意以下两个步骤
为你的 table
定义 id, 并添加在 btn_export
函数中替换 table1
,
定义 button
组件, 并添加 onclick
事件绑定函数 btn_export
<script>
function btn_export() {
var table1 = document.querySelector("#table1");
var sheet = XLSX.utils.table_to_sheet(table1);//将一个table对象转换成一个sheet对象
openDownloadDialog(sheet2blob(sheet),'下载.xlsx');
}
// 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
function sheet2blob(sheet, sheetName) {
sheetName = sheetName || 'sheet1';
var workbook = {
SheetNames: [sheetName],
Sheets: {}
};
workbook.Sheets[sheetName] = sheet; // 生成excel的配置项
var wopts = {
bookType: 'xlsx', // 要生成的文件类型
bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
type: 'binary'
};
var wbout = XLSX.write(workbook, wopts);
var blob = new Blob([s2ab(wbout)], {
type: "application/octet-stream"
}); // 字符串转ArrayBuffer
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
return blob;
}
function openDownloadDialog(url, saveName) {
if (typeof url == 'object' && url instanceof Blob) {
url = URL.createObjectURL(url); // 创建blob地址
}
var aLink = document.createElement('a');
aLink.href = url;
aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
var event;
if (window.MouseEvent) event = new MouseEvent('click');
else {
event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
aLink.dispatchEvent(event);
}
</script>
<button class="layui-btn-radius" onclick="btn_export()">导出excel文档button>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>项目信息浏览</title>
<!-- Meta tag Keywords -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Custom-Files -->
<link rel="stylesheet" href="../assets/css/layui.css">
<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../css/admin.css">
<!-- //Custom-Files -->
<script src="../index.js" data-main="home"></script>
<script src="../assets/layui.js"></script>
<script src="../js/xlsx.core.min.js"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
//layui实现全选
layui.use('form', function () {
const form = layui.form;
/*此处对应页面属性lay-filter="allChoose" allChoose可更改为任意名*/
form.on('checkbox(allChoose)', function (data) {
/*此处为匹配页面属性class="itemSelect" 可任意更换*/
$("input[class='itemSelect']").each(function () {
this.checked = data.elem.checked;
});
form.render('checkbox');
});
});
</script>
<script>
function btn_export() {
var table1 = document.querySelector("#table1");
var sheet = XLSX.utils.table_to_sheet(table1);//将一个table对象转换成一个sheet对象
openDownloadDialog(sheet2blob(sheet),'下载.xlsx');
}
// 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
function sheet2blob(sheet, sheetName) {
sheetName = sheetName || 'sheet1';
var workbook = {
SheetNames: [sheetName],
Sheets: {}
};
workbook.Sheets[sheetName] = sheet; // 生成excel的配置项
var wopts = {
bookType: 'xlsx', // 要生成的文件类型
bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
type: 'binary'
};
var wbout = XLSX.write(workbook, wopts);
var blob = new Blob([s2ab(wbout)], {
type: "application/octet-stream"
}); // 字符串转ArrayBuffer
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
return blob;
}
function openDownloadDialog(url, saveName) {
if (typeof url == 'object' && url instanceof Blob) {
url = URL.createObjectURL(url); // 创建blob地址
}
var aLink = document.createElement('a');
aLink.href = url;
aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
var event;
if (window.MouseEvent) event = new MouseEvent('click');
else {
event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
aLink.dispatchEvent(event);
}
</script>
<%-- 获取layui属性依赖--%>
<script>
layui.use('form', function () {
var form = layui.form;
form.render('select'); //刷新select选择框渲染
//各种基于事件的操作,下面会有进一步介绍
});
layui.use('element', function(){
var element = layui.element;
//一些事件触发
element.on('tab(demo)', function(data){
console.log(data);
});
});
</script>
</head>
<body>
<div class="container" style='margin-top:30px;width:auto;height:800px;overflow-x:auto;overflow-y:auto'>
<!--查询 -->
<form class="layui-form" action="${pageContext.request.contextPath}/project/loadRank">
<div class="layui-form-item">
<label class="layui-form-label">比赛</label>
<div class="layui-input-inline">
<select name="match" lay-verify="required" >
<c:forEach items="${matchList}" var="match" varStatus="s">
<option value="${match.title}">${match.title}</option>
</c:forEach>
</select>
</div>
<button class="layui-btn" lay-submit lay-filter="formDemo">获取</button>
</div>
</form>
<!-- 表格 -->
<table id="table1" lay-skin="line" class="layui-table" lay-even lay-skin="nob" id="userListTable" lay-size="sm">
<!-- 列宽度 -->
<colgroup>
<col width="50">
<col width="50">
<col width="110">
<col width="110">
<col width="110">
<col width="110">
<col width="120">
<col>
</colgroup>
<!-- 表头 -->
<tr class="info" style=" text-align: center;">
<th lay-size="5px">排名</th>
<th>名称</th>
<th>参加比赛名称</th>
<th>项目类型</th>
<th>学校</th>
<th>负责人</th>
<th>联系电话</th>
<th>成员</th>
<th>申请日期</th>
<th>项目描述</th>
<th>分数</th>
</tr>
<c:forEach items="${projects}" var="project" varStatus="s">
<tr>
<td>${s.count}</td>
<td>${project.title}</td>
<td>${project.match}</td>
<td>${project.type}</td>
<td>${project.college}</td>
<td>${project.person}</td>
<td>${project.phone}</td>
<td>${project.member}</td>
<td>
<fmt:formatDate value="${project.date}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td>${project.desc}</td>
<td>${project.score}</td>
</tr>
</c:forEach>
</table>
<button class="layui-btn-radius" onclick="btn_export()">导出excel文档</button>
</div>
<script src="../js/jquery-2.1.0.min.js" type="text/javascript"></script>
<script src="../js/bootstrap.min.js" type="text/javascript"></script>
</div>
</body>
</html>
OVER~