如何使用JavaScript實現前端導入和導出excel文件


 

一、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


 

 

以上就是使用SpreadJS,實現前端導入和導出excel文件的具體步驟和示例代碼,其他如Excel公式、圖表、條件格式、JSON序列化與反序列化、狀態欄等功能,可以在SpreadJS官網了解更多。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM