前端必讀3.0:如何在 Angular 中使用SpreadJS實現導入和導出 Excel 文件

在之前的文章中,我們爲大家分別詳細介紹了在JavaScript、React中使用SpreadJS導入和導出Excel文件的方法,作爲帶給廣大前端開發者的“三部曲”,本文我們將爲大家介紹該問題在Angular中的實現。
Excel 電子表格自 1980 年代以來一直爲各行業所廣泛使用,至今已擁有超過3億用戶,大多數人都熟悉 Excel 電子表格體驗。許多企業在其業務的各個環節中使用了 Excel 電子表格進行預算和規劃。
通常情況下,剛開始時我們的業務流程中的數據簡單,也不涉及複雜的格式和數據關係。但隨着組織的發展,可能很難不開始依賴 Excel 的功能。

在你的應用程序中安裝 SpreadJS 組件

完整的Demo請點擊此處下載:
https://gcdn.grapecity.com.cn/forum.php?mod=attachment&aid=MjM0MDU3fDk2NDQyNTkyfDE2NjM5MjI3NjF8NjI2NzZ8OTk3MTg%3D

應該注意的是,由於我們使用的是 Angular CLI,我們需要確保它與 NPM 一起安裝:

npm install -g @angular/cli

由於我們將使用 SpreadJS 的 Excel 導入和導出功能,因此我們需要 ExcelIO 組件。你可以使用 NPM 安裝它和基本的 SpreadJS 文件:

npm install @grapecity/spread-sheets @grapecity/spread-excelio @grapecity/spread-sheets-angular

實例化 SpreadJS 組件

SpreadJS 可以添加到 app.component.html 頁面,如下所示:

<gc-spread-sheets [backColor]=”spreadBackColor” [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)">
</gc-spread-sheets>

實例化 SpreadJS 組件並在 app.component.ts 文件中創建 ExcelIO 類的對象,代碼如下:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  spreadBackColor = 'aliceblue';
  hostStyle = {
    width: '95vw',
    height: '80vh'
  };
  private spread;
  private excelIO;

  constructor() {
    this.spread = new GC.Spread.Sheets.Workbook();
    this.excelIO = new Excel.IO();
  }

  workbookInit(args: any) {
    const self = this;
    self.spread = args.spread;
    const sheet = self.spread.getActiveSheet();
    sheet.getCell(0, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(0, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(0, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(0, 3).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 3).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 3).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 3).text('Test Excel').foreColor('blue');
 }

創建一個接受 XLSX 文件的輸入元素

對於導入,我們將創建一個接受 XLSX 文件的輸入元素。讓我們在 app.component.html 中添加以下代碼:

<div class='loadExcelInput'>
  <p>Open Excel File</p>
  <input type="file" name="files[]" multiple id="jsonFile" accept=".xlsx" (change)="onFileChange($event)" />
</div>

添加導入代碼

ExcelIO 對象打開所選文件並以 JSON 格式返回結果。這個 JSON 數據可以被 SpreadJS 直接理解,所以我們將在 onFileChange() 函數中爲 change 事件編寫導入代碼,如下所示:

onFileChange(args: any) {
  const self = this, file = args.srcElement && args.srcElement.files && args.srcElement.files[0];
  if (self.spread && file) {
    self.excelIO.open(file, (json: any) => {
      self.spread.fromJSON(json, {});
      setTimeout(() => {
        alert('load successfully');
      }, 0);
    }, (error: any) => {
      alert('load fail');
    });
  }
}

添加導出代碼

同樣,讓我們添加一個按鈕來處理導出功能。要添加導出按鈕,我們可以使用:

<div class='exportExcel'>
  <p>Save Excel File</p>
  <button (click)="onClickMe($event)">Save Excel!</button>
</div>

我們還需要處理這個按鈕的點擊事件並在那裏編寫我們的代碼。 SpreadJS 將數據保存爲 JSON,ExcelIO 可以使用 JSON 將其保存爲 BLOB。稍後,需要將此 blob 數據傳遞給文件保護程序組件的 saveAs() 函數:

onClickMe(args: any) {
  const self = this;
  const filename = 'exportExcel.xlsx';
  const json = JSON.stringify(self.spread.toJSON());
  self.excelIO.save(json, function (blob) {
    saveAs(blob, filename);
  }, function (error: any) {
    console.log(error);
  });
}

應該注意的是,我們使用了文件保護程序組件來實現導出功能。要在你的項目中包含文件保護程序,請按照以下步驟操作:

  1. 運行“npm install file-saver –save”命令
  2. 運行“npm install @types/file-saver –save-dev”命令
  3. 將此第三方庫添加到“.angular.json”
    "scripts": ["./node_modules/file-saver/FileSaver.js"]**
  4. 導入組件
import {saveAs} from 'file-saver'; 

現在已經可以在 Angular 中使用 SpreadJS 成功導入和導出 Excel 文件了。

更多純前端表格在線demo示例 :https://demo.grapecity.com.cn/spreadjs/gc-sjs-samples/index.html
純前端表格應用場景:https://www.grapecity.com.cn/developer/spreadjs#scenarios
移動端示例(可掃碼體驗):http://demo.grapecity.com.cn/spreadjs/mobilesample/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章