在之前的文章中,我們為大家分别詳細介紹了在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');
}
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsQTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5yMyczM2ATOjJDOyI2N3QmMzYzX2ATOwcTMzIzLclDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
建立一個接受 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);
});
}
應該注意的是,我們使用了檔案保護程式元件來實作導出功能。要在你的項目中包含檔案保護程式,請按照以下步驟操作:
- 運作“npm install file-saver –save”指令
- 運作“npm install @types/file-saver –save-dev”指令
-
将此第三方庫添加到“.angular.json”
"scripts": ["./node_modules/file-saver/FileSaver.js"]**
- 導入元件
import {saveAs} from 'file-saver';