本项目实现功能:VUE框架中 嵌入表格控件SpreadJS,实现导入Excel、导出Excel、导出PDF、打印表格等
初始化VUE项目
参考文章:3分钟创建 SpreadJS 的 Vue 项目
项目运行效果:
本地的一个Excel文件:
导入Excel在项目中:
文章中的SpreadJS 版本是V11 的,现在最新版本已经是V13版本,我的例子中应用了SpreadJSV 12.2.5的版本,package.json 中添加的引用如下:
"dependencies": {
"@grapecity/spread-excelio": "12.2.5",
"@grapecity/spread-sheets": "12.2.5",
"@grapecity/spread-sheets-pdf": "^12.2.5",
"@grapecity/spread-sheets-print": "12.2.5",
"@grapecity/spread-sheets-resources-zh": "12.2.5",
"@grapecity/spread-sheets-vue": "12.2.5",
"@grapecity/spread-sheets-charts": "12.2.5" ,
"file-saver": "2.0.2",
"jquery": "2.2.1",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
执行npm install 命令安装SpreadJS
导出PDF功能注意事项
- 安装相同版本的 pdf的包: "@grapecity/spread-sheets-pdf"
- 在需要打印的页面引入该包: import "@grapecity/spread-sheets-pdf";
- 引入该包需要注意引入顺序,先引入 @grapecity/spread-sheets和 grapecity/spread-sheets-print
- 需引入第三方插件file-saver : import FaverSaver from 'file-saver'
- 如下几行代码可实现导出PDF功能
savePdf(){
let self = this;
let jsonString = JSON.stringify(self.spread.toJSON());
let printSpread = new GC.Spread.Sheets.Workbook();
printSpread.fromJSON(JSON.parse(jsonString));
printSpread.savePDF(function(blob) {
// window.open(URL.createObjectURL(blob))
FaverSaver.saveAs(blob, 'Hello.pdf')
}, function(error) {
console.log(error);
}, {
title: 'Print',
});
}
导入导出Excel
- 安装相关的包: "@grapecity/spread-excelio"、 "file-saver"
- 在页面中引入: import ExcelIO from '@grapecity/spread-excelio'、import FaverSaver from 'file-saver'
- 如下代码可实现导入导出Excel:
exportXlsx () {
let ex = new ExcelIO.IO()
let json = this.spread.toJSON()
ex.save(json, function (blob) {
FaverSaver.saveAs(blob, 'export.xlsx')
}, function (e) {
console.log(e)
})
},
importXlsx(){
let self = this;
var excelIO = new ExcelIO.IO();
console.log(excelIO);
const excelFile = document.getElementById("fileDemo").files[0];
excelIO.open(excelFile, function (json) {
let workbookObj = json;
self.spread.fromJSON(workbookObj);
}, function (e) {
alert(e.errorMessage);
});
}