V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
powertoolsteam
V2EX  ›  推广

如何使用 JavaScript 实现前端导入和导出 excel 文件

  •  
  •   powertoolsteam · 2019-07-02 16:00:30 +08:00 · 1546 次点击
    这是一个创建于 1775 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一、SpreadJS 简介

    SpreadJS 是一款基于 HTML5 的纯 JavaScript 电子表格和网格功能控件,以“高速低耗、纯前端、零依赖”为产品特色,可嵌入任何操作系统,同时满足 .NET 、Java、响应式 Web 应用及移动跨平台的表格数据处理和类 Excel 的表格应用开发,为终端用户带来亲切的 Excel 体验。本文将以 xlsx 文件格式为例,展示如何使用 SpreadJS 实现前端导入和导出 excel 文件。

    主要功能

    1. 功能、UI 与 Excel 高度类似
    2. 兼容 450 种以上的 Excel 公式
    3. 符合 UMD 规范,可按需加载
    4. 完善的数据可视化,支持形状、图表、迷你图
    5. 纯前端导入、导出 Excel 文件
    6. 使用 HTML5 图形( Canvas )绘制界面,具备高性能和响应速度

    安装包目录结构

    ├── Spread.Sheets        SpreadJS 产品包
    
    │          └── Designer      SpreadJS 表格设计器
    
    │                        ├── Spread.Sheets-Designer.12.0.0.AppImage   [Mac]
    
    │                        ├── Spread.Sheets-Designer.12.0.0.dmg           [Linux]
    
    │                        └── Spread.Sheets-Designer.12.0.0                 [Windows]
    
    │         └── Spread.Sheets.Docs.12.0.0    SpreadJS 表格接口文档
    
    │                        ├── content
    
    │                        └── index   
    
    │         └── Spread.Sheets.Release.12.0.0    SpreadJS 表格 JavaScript 库 /演示用例
    
    │                        ├── css              样式文件
    
    │                        ├── definition   TS 引用文件
    
    │                        ├── readme
    
    │                        ├── samples      示例代码(包括原生 JS,Angular,Vue,React )
    
    │                        ├── scripts         JS 文件
    
    │                        ├── GrapeCity-EULA
    
    │                        └── LICENSE
    

    如何使用

    Spread.Sheets 不依赖任何第三方组件。它只需要引用下列文件:gc.spread.sheets.xx.x.x.css ,gc.spread.sheets.all.xx.x.x.min.js 。

    <link rel="styleSheet" href="gc.spread.sheets.xx.x.x.css" />
    
    <script src="gc.spread.sheets.all.xx.x.x.min.js" type="text/javascript"></script>
    
    <script src="gc.spread.sheets.resources.zh.xx.x.x.min.js" type="text/javascript"></script>
    

    页面的 body 元素中添加一个 DOM 元素作为它的容器。

    <div id="ss" style="width:100%; height:360px;border: 1px solid gray;"></div>
    

    用代码“ new GC.Spread.Sheets.Workbook(document.getElementById('ss'), { sheetCount: 1 })”来初始化 Spread。

    window.onload = function () {
    
        var spread = new GC.Spread.Sheets.Workbook(document.getElementById('ss'), { sheetCount: 1 });
    
    };
    

    初始化 SpreadJS 在线示例

    二、前端导入导出 Excel

    实现前端导入导出只需要引入 gc.spread.excelio 库,使用 excelIO.open 和 excelIO.save 两个方法即可,不需要配置任何选项,代码十分简洁易懂。

    具体步骤如下:

    前端导入导出支持将 Spread json 导出为 excel 文件(.xlsx)和将 excel 文件导入为 Spread json.

    使用前端导入导出, 你需要将相关的 js 文件添加的 document 的 head 区域。例如:

    <head>
    
       ...
    
       <script src='.../spreadjs/gc.spread.sheets.all.x.xx.xxxxx.x.min.js' type='text/javascript'></script>
    
       <script src='.../spreadjs/plugins/gc.spread.excelio.x.xx.xxxxx.x.min.js' type='text/javascript'></script>
    
    </head>
    

    初始化 Workbook 实例和 ExcelIO 实例:

    var spread = new GC.Spread.Sheets.Workbook(document.getElementById('ss'));
    
    var excelIo = new GC.Spread.Excel.IO();
    

    接下来你就可以使用 open 方法将 excel 文件导入为 spread json,使用 save 方法将 spread json 导出为 excel 文件。例如:

    //import excel file to Spread.Sheets json
    
    excelIo.open(excelFile, function (json) {
    
        var workbookObj = json;
    
        workbook.fromJSON(workbookObj);
    
    }, function (e) {
    
        // process error
    
        console.log(e);
    
    });
    
    //export Spread.Sheets json to excel file
    
    excelio.save(json, function (blob) {
    
        //do whatever you want with blob
    
        //such as you can save it
    
    }, function (e) {
    
        //process error
    
        console.log(e);
    
    });
    

    同时,你还可打开或保存一个带有密码保护的 excel 文件,只需要在 open 和 save 方法中传入参数 options{password:xxxx}即可。例如:

    //import excel file to Spread.Sheets json
    
    excelIo.open(excelFile, function (json) {
    
        var workbookObj = json;
    
        workbook.fromJSON(workbookObj);
    
    }, function (e) {
    
        // process error
    
        console.log(e);
    
    },{password:xxxx});
    
    //export Spread.Sheets json to excel file
    
    excelio.save(json, function (blob) {
    
        //do whatever you want with blob
    
        //such as you can save it
    
    }, function (e) {
    
        //process error
    
        console.log(e);
    
    },{password:xxxx});
    

    前端导入导出 Excel 的示例源码及数据源下载:

    三、处理单元格合并

    一般来说,前端生成 excel 而不是 csv,其最主要的原因都是为了解决 csv 不能实现单元格合并的问题,假设我们要生成带有单元格格式的 Excel 文件,也可以通过 SpreadJS 内置属性实现:

    调用 addSpan 方法来合并指定区域的单元格, 以此来构建一个新的更大的单元格, 参见以下示例代码:

    // Merge cells and set label
    
    sheet.addSpan(1, 4, 1, 7);
    
    sheet.setValue(1, 4, "Goods");
    
    // Merge cells across multi rows (3) and columns (4)
    
    sheet.addSpan(20, 1, 3, 4);
    
    sheet.getCell(20, 1).value("Demo").hAlign.vAlign;
    

    调用 removeSpan 方法来分解指定包含合并的单元格:

    sheet.removeSpan(20, 1);
    

    Workbook 的 allowUserDragMerge 选项表明是否允许通过鼠标拖拽来合并单元格。把 allowUserDragMerge 改为 true,在选择区域边缘处会出现一个特殊的标记。

    // default value is false
    
    spread.options.allowUserDragMerge = true;
    

    备注: 确定你要展现在合并单元格中的信息在合并前处于合并区域的最左上单元格, 合并单元格中的其他单元格信息将被隐藏, 直到合并信息被分解(与 Excel 相同)。

    处理单元格合并的示例源码及数据源下载:cellSpan.html

    四、自定义 Excel 的文件样式

    Spread.Sheets 提供一个样式的类, 其中包含很多可配置属性, 如前景色、背景色等。

    你可以通过这些属性,构造一个样式并设置不同的参数, 示例代码如下:

    var style = new GC.Spread.Sheets.Style();
    
    style.backColor = 'red';
    
    style.foreColor = 'green';
    
    style.isVerticalText = 'true';
    

    同样,你也可以将此样式设置给单元格, 行, 或者列:

    //set style to cell.
    
    sheet.setStyle(5, 5, style, GC.Spread.Sheets.SheetArea.viewport);
    
    
    
    //set style to row.
    
    sheet.setStyle(5, -1, style, GC.Spread.Sheets.SheetArea.viewport);
    
    
    
    //set style to column.
    
    sheet.setStyle(-1, 5, style, GC.Spread.Sheets.SheetArea.viewport);
    

    样式在不同的层级结构中具有不同的优先级别: 单元格 > 行 > 列。

    Spread.Sheets 支持给样式设置一个名称, 并将这个命名过的样式加入到表单的名称样式集合中。这样让样式的使用和管理更方便。

    你可以构造一个名称样式, 并将此样式添加到表单或者 Spread 控件的名称样式集合中,如:

    var style = new GC.Spread.Sheets.Style();
    
    style.name = 'style1';
    
    style.backColor = 'red';
    
    
    
    //add to sheet's named style collection.
    
    sheet.addNamedStyle(style);
    
    //add to spread's named style collection.
    
    spread.addNamedStyle(style)
    

    当名称样式添加到表单名称样式集合中后, 可以通过样式的名称找到它:

    sheet.getNamedStyle('style1');
    
    spread.getNamedStyle('style1')
    

    如果名称样式不再使用, 你也可以将其从名称集合中删除掉:

    sheet.removeNamedStyle('style1');
    
    spread.removeNamedStyle('style1')
    

    自定义 Excel 文件样式的示例源码:style.html

    五、数据绑定

    Spread.Sheets 支持绑定数据源到表单(绑定类型有表单级别绑定和单元格级别绑定两种。)

    你可以使用 setDataSource 和 getDataSource 方法来设置获取数据源。 在设置数据源之前, 你可以使用 autoGenerateColumns 方法来控制是否自动生成绑定列。 例如:

    var customers = [
    
       { ID:0, Name:'A', Info1:'Info0' },
    
       { ID:1, Name:'B', Info1:'Info1' },
    
       { ID:2, Name:'C', Info1:'Info2' },
    
    ];
    
    sheet.autoGenerateColumns = true;
    
    sheet.setDataSource(customers);
    

    你也可以使用 getDataItem 方法来获取指定行的数据信息。

    你按照如下方式将数据字段绑定到指定的列:

    var datasource = [
    
       { name: 'Alice', age: 27, birthday: '1985/08/31', position: 'PM' }
    
    ];
    
    // bindColumn one by one
    
    var nameColInfo = { name: 'name', displayName: 'Display Name', size: 70 };
    
    var ageColInfo = { name: 'age', displayName: 'Age', size: 40, resizable: false };
    
    var birthdayColInfo = { name: 'birthday', displayName: 'Birthday', formatter: 'd/M/yy', size: 120 };
    
    var positionColInfo = { name: 'position', displayName: 'Position', size: 50, visible: false };
    
    sheet.autoGenerateColumns = false;
    
    sheet.setDataSource(datasource);
    
    sheet.bindColumn(0, nameColInfo);
    
    sheet.bindColumn(1, birthdayColInfo);
    
    sheet.bindColumn(2, ageColInfo);
    
    sheet.bindColumn(3, positionColInfo);
    
    
    
    // or use bindColumns to bind all custom columns
    
    var colInfos = [
    
       { name: 'position', displayName: 'Position', size: 50, visible: false },
    
       { name: 'name', displayName: 'Display Name', size: 70 },
    
       { name: 'birthday', displayName: 'Birthday', formatter: 'd/M/yy', size: 120 },
    
       { name: 'age', displayName: 'Age', size: 40, resizable: false },
    
    ];
    
    sheet.autoGenerateColumns = false;
    
    sheet.setDataSource(datasource);
    
    sheet.bindColumns(colInfos);
    

    数据绑定的示例源码:sheetLevelBinding.html

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2920 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:23 · PVG 19:23 · LAX 04:23 · JFK 07:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.