基于SpreadJS构建纯前端Excel查看器:从引入到功能实现
本文详细介绍如何利用SpreadJS纯前端表格控件在Web应用中构建Excel查看器。内容涵盖通过本地文件或NPM引入SpreadJS组件,配置HTML UI界面,实现Excel文件的导入与导出功能,并演示如何为受密码保护的Excel文件提供密码输入支持,以及对工作簿进行数据保护以防止用户修改。
前言
在当前Web应用开发领域,处理与展示Excel文件是高频需求。为提升用户体验,开发者常需在Web端集成JavaScript Excel查看器。本文将演示如何借助葡萄城提供的纯前端表格控件SpreadJS来实现这一功能。
项目结构
本项目由三个核心文件组成:HTML文件、JavaScript文件以及CSS文件。
1.引入SpreadJS
(1)本地文件引入
SpreadJS支持从官网下载并集成至项目中。下载后,解压ZIP包并将JS和CSS文件复制到代码目录,重点关注以下文件。
- gc.spread.sheets.all.xx.x.x.min.js
- gc.spread.sheets.io.xx.x.x.min.js
- gc.spread.sheets.excel2013white.xx.x.x.css
将这些文件放置于程序文件夹后,即可在代码中进行引用。
<link rel="stylesheet" type="text/css" href="./styles/gc.spread.sheets.excel2013white.css" rel="external nofollow" >
<script src="./scripts/gc.spread.sheets.all.min.js" type="text/javascript"></script>
<script src="./scripts/gc.spread.sheets.charts.min.js" type="text/javascript"></script>
<script src="./scripts/gc.spread.sheets.shapes.min.js" type="text/javascript"></script>
<script src="./scripts/gc.spread.sheets.io.min.js" type="text/javascript"></script>
下载的示例中,默认已配置此方式,无需额外修改。
(2)NPM引用
另一种方式是通过NPM引入SpreadJS。可使用以下命令安装依赖:
npm install @grapecity/spread-sheets @grapecity/spread-sheets-io @grapecity/spread-sheets-charts @grapecity/spread-sheets-shapes
随后,在代码中按如下方式引用这些文件:
<link rel= "stylesheet" type= "text/css" href= "./node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css" >
<script src="./node_modules/ @grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js" type="text/javascript"></script>
<script src="./node_modules/@grapecity/spread-sheets-io /dist/gc.spread.sheets.io.min.js" type="text/javascript"></script>
<script src="./node_modules/@grapecity/spread-sheets-charts/dist/gc.spread .sheets.charts.min.js" type="text/javascript"></script>
<script src="./node_modules/@grapecity/spread-sheets-shapes/dist/gc.spread.sheets.shapes.min .js" type="text/javascript"></script>
2.创建HTML内容
引用文件后,即可组合HTML页面与CSS样式。样式部分已预先创建好:
body {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.sample-tutorial {
position: relative;
height: 100%;
overflow: hidden;
}
.sample-container {
width: calc(100% - 280px);
height: 100%;
float: left;
}
.sample-spreadsheets {
width: 100%;
height: calc(100% - 25px);
overflow: hidden;
}
.options-container {
float: right;
width: 280px;
height: 100%;
box-sizing: border-box;
background: #fbfbfb;
overflow: auto;
}
.sample-options {
z-index: 1000;
}
.inputContainer {
width: 100%;
height: auto;
border: 1px solid #eee;
padding: 6px 12px;
margin-bottom: 10px;
box-sizing: border-box;
}
.settingButton {
color: #fff;
background: #82bc00;
outline: 0;
line-height: 1.5715;
position: relative;
display: inline-block;
font-weight: 400;
white-space: nowrap;
text-align: center;
height: 32px;
padding: 4px 15px;
font-size: 14px;
border-radius: 2px;
user-select: none;
cursor: pointer;
border: 1px solid #82bc00;
box-sizing: border-box;
margin-bottom: 10px;
margin-top: 10px;
}
.settingButton:hover {
color: #fff;
border-color: #88b031;
background: #88b031;
}
.settingButton:disabled {
background: #e2dfdf;
border-color: #ffffff;
}
.options-title {
font-weight: bold;
margin: 4px 2px;
}
#selectedFile {
display: none;
}
select, input[type="text"], input[type="number"] {
display: inline-block;
margin-left: auto;
width: 120px;
font-weight: 400;
outline: 0;
line-height: 1.5715;
border-radius: 2px;
border: 1px solid #F4F8EB;
box-sizing: border-box;
}
.passwordIpt {
margin-top: 10px;
height: 25px;
}
.passwordIpt[warning="true"] {
border-color: red;
}
.passwordIpt[warning="true"]::placeholder {
color: red;
opacity: 0.8;
}
@keyframes shake {
0% { transform: translate(1px, 1px) rotate(0deg); }
10% { transform: translate(-1px, -2px) rotate(-1deg); }
20% { transform: translate(-3px, 0px) rotate(1deg); }
30% { transform: translate(3px, 2px) rotate(0deg); }
40% { transform: translate(1px, -1px) rotate(1deg); }
50% { transform: translate(-1px, 2px) rotate(-1deg); }
60% { transform: translate(-3px, 1px) rotate(0deg); }
70% { transform: translate(3px, 1px) rotate(-1deg); }
80% { transform: translate(-1px, -1px) rotate(1deg); }
90% { transform: translate(1px, 2px) rotate(0deg); }
100% { transform: translate(1px, 1px) rotate(0deg); }
}
#warningBox {
color: red;
}
接下来,添加网页所需的按钮与UI元素,主要包括:
- SpreadJS容器
- 状态栏
- 导入区域
- 密码输入框
- 文件选择按钮
- 导入按钮
- 导出区域
- 密码输入框
- 导出按钮
添加HTML标签时,可为每个元素应用合适的样式:
<body>
<div class="sample-tutorial">
<div class="sample-container">
<div id="ss" class="sample-spreadsheets"></div>
<div id="statusBar"></div>
</div>
<div class="options-container">
<div class="option-row">
<div class="inputContainer">
<div class="options-title">Import:</div>
<input class="passwordIpt" id="importPassword" type="password" placeholder="Password" disabled>
<br>
<div id="warningBox"></div>
<input id="selectedFile" type="file" accept=".xlsx" />
<button class="settingButton" id="selectBtn">Select</button>
<button class="settingButton" id="importBtn" disabled>Import</button>
</div>
<div class="inputContainer">
<div class="options-title">Export:</div>
<input class="passwordIpt" id="exportPassword" type="password" placeholder="Password">
<br>
<button class="settingButton" id="exportBtn">Export</button>
</div>
</div>
</div>
</div>
</body>
3.初始化
完成HTML内容与SpreadJS引用后,即可开始初始化SpreadJS实例,并在app.js文件中添加Excel导入代码。
window.onload = function () {
let spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
}
4.添加按钮和功能
为实现应用目标,需添加以下变量:
const $ = selector => document.querySelector(selector);
const listen = (host, type, handler) => host.addEventListener(type, handler);
在window.onload函数中创建变量,以引用不同的HTML元素:
const importPassword = $('#importPassword');
const selectBtn = $('#selectBtn');
const fileSelect = $('#selectedFile');
const importBtn = $('#importBtn');
const warningBox = $('#warningBox');
const exportPassword = $('#exportPassword');
const exportBtn = $('#exportBtn');
为文件选择按钮和输入框添加事件监听函数,并处理密码错误的提示:
listen(selectBtn, "click", () => fileSelect.click());
const fileSelectedHandler = () => {
importPassword.disabled = false;
importBtn.disabled = false;
}
listen(fileSelect, 'change', fileSelectedHandler);
const wrongPasswordHandler = message => {
importPassword.setAttribute('warning', true);
importPassword.style.animation = "shake 0.5s";
setTimeout(() => importPassword.style.animation = "", 500);
warningBox.innerText = message;
importPassword.value = '';
};
listen(importPassword, 'focus', () => {
warningBox.innerText = '';
importPassword.removeAttribute('warning');
});
5.导入Excel文件
现在编写将Excel文件导入SpreadJS实例的代码。鉴于可能导入受密码保护的文件,调用SpreadJS的import函数时需考虑此情况。可在import时添加事件处理程序:
const importFileHandler = () => {
let file = fileSelect.files[0];
if (!file) return ;
spread.import(file, console.log, error => {
if (error.errorCode === GC.Spread.Sheets.IO.ErrorCode.noPassword || error.errorCode === GC.Spread.Sheets.IO.ErrorCode.invalidPassword) {
wrongPasswordHandler(error.errorMessage);
}
}, {
fileType: GC.Spread.Sheets.FileType.excel,
password: importPassword.value
});
};
listen(importBtn, 'click', importFileHandler);
6.导出Excel文件
与导入类似,支持用户在导出Excel时输入保护密码,只需将密码传入SpreadJS的export函数。同样为其添加事件处理程序:
const exportFileHandler = () => {
let password = exportPassword.value;
spread.export(blob => saveAs(blob, (password ? 'encrypted-' : '') + 'export.xlsx'), console.log, {
fileType: GC.Spread.Sheets.FileType.excel,
password: password
});
};
listen(exportBtn, 'click', exportFileHandler);
7.数据保护
我们还可通过添加按钮来保护工作簿当前表单,从而阻止用户修改数据。稍作修改,此功能可适配多种需求,但本示例仅保护活动表单。与其他按钮类似,需添加点击事件处理程序,对于SpreadJS,可添加保护选项:
const protectHandler = () => {
var option = {
allowSelectLockedCells:true,
allowSelectUnlockedCells:true,
allowFilter: true,
allowSort: false,
allowResizeRows: true,
allowResizeColumns: false,
allowEditObjects: false,
allowDragInsertRows: false,
allowDragInsertColumns: false,
allowInsertRows: false,
allowInsertColumns: false,
allowDeleteRows: false,
allowDeleteColumns: false,
allowOutlineColumns: false,
allowOutlineRows: false
};
spread.getActiveSheet().options.protectionOptions = option;
spread.getActiveSheet().options.isProtected = true;
};
listen(protectBtn, 'click', protectHandler);
8.运行程序
最后,运行程序。由于使用纯JS和HTML编写,可直接在浏览器中打开HTML文件:

点击“Select”按钮选择Excel文件加载,然后点击“Import”按钮将其导入SpreadJS:

接着,在导出密码输入框中输入密码,点击“Export”按钮:

如需查看完整源码,可访问此Gitee地址。
以上为JavaScript使用SpreadJS创建Excel查看器的详细内容,更多关于JavaScript SpreadJS创建Excel查看器的资料请关注本站其它相关文章!
JS中使用位运算(~~)和一元加号(+)快速转换字符串为整数
2026-11-03 22:41:12
怎么使用命令行批量格式化项目中的JS文件
2026-11-03 19:04:42
JS代码美化后报错怎么办?常见格式化冲突解决方法
2026-11-03 18:47:01
不用moment.js,怎么用原生JS Intl API格式化时间戳
2026-11-03 18:10:30
原生JS与dayjs获取当前日期的代码对比
2026-11-03 17:57:26
