在上一篇文章中,我们详细介绍了如何在JavaScript和React中使用SpreadJS导入导出Excel文件,作为对前端开发者的“三部曲”,本文我们将介绍这个问题在Angular中的实现。自1980年代以来,Excel电子表格已在各行各业使用,如今拥有超过3亿用户,大多数人都熟悉Excel电子表格体验。许多企业使用Excel电子表格对其业务的各个方面进行预算和规划。通常,我们业务流程中的数据一开始都是简单的,不涉及复杂的格式和数据关系。但是随着组织的发展,很难不开始依赖Excel的功能。在你的应用中安装SpreadJS组件请点击这里下载完整的demo:https://gcdn.grapecity.com.cn...需要注意的是,由于我们使用的是AngularCLI,所以需要确保它是与使用NPM安装兼容:npminstall-g@angular/cli因为我们将使用SpreadJS的Excel导入和导出功能,所以我们需要ExcelIO组件。您可以使用NPM安装它和基本的SpreadJS文件:npminstall@grapecity/spread-sheets@grapecity/spread-excelio@grapecity/spread-sheets-angular如下所示:实例化SpreadJS组件并运行它在app.component.ts文件中创建一个ExcelIO类对象,代码如下:@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent{spreadBackColor='aliceblue';hostStyle={宽度:'95vw',高度:'80vh'};私人传播;私人excelIO;constructor(){this.spread=newGC.Spread.Sheets.Workbook();this.excelIO=newExcel.IO();}workbookInit(args:any){constself=this;self.spread=args.spread;constsheet=self.spread.getActiveSheet();床单。getCell(0,0).text('测试Excel').foreColor('blue');sheet.getCell(1,0).text('测试Excel').foreColor('blue');sheet.getCell(2,0).text('测试Excel').foreColor('blue');sheet.getCell(3,0).text('测试Excel').foreColor('blue');sheet.getCell(0,1).text('测试Excel').foreColor('blue');sheet.getCell(1,1).text('测试Excel').foreColor('blue');sheet.getCell(2,1).text('测试Excel').foreColor('blue');sheet.getCell(3,1).text('测试Excel').foreColor('blue');sheet.getCell(0,2).text('测试Excel').foreColor('blue');sheet.getCell(1,2).text('测试Excel').foreColor('blue');sheet.getCell(2,2).text('测试Excel').foreColor('blue');sheet.getCell(3,2).text('测试Excel').foreColor('blue');sheet.getCell(0,3).text('测试Excel').foreColor('blue');sheet.getCell(1,3).text('测试Excel').foreColor('blue');sheet.getCell(2,3).text('测试Excel').foreColor('blue');sheet.getCell(3,3).text('测试Excel').foreColor('blue');}创建一个接收XLSX文件的输入元元素对于导入,我们将创建一个接收XLSX文件的输入input元素让我们在app.component.html中添加以下代码:OpenExcelFile
添加导入代码ExcelIO对象,打开选中的文件,返回JSON格式的结果。SpreadJS可以直接理解这个JSON数据,所以我们将在onFileChange()函数中写入change事件的导入代码如下:srcElement.files&&args.srcElement.files[0];if(self.spread&&file){self.excelIO.open(file,(json:any)=>{self.spread.fromJSON(json,{});setTimeout(()=>{alert('加载成功');},0);},(error:any)=>{alert('loadfail');});}}添加导出代码我们再次添加一个按钮来处理导出功能。要添加导出按钮,我们可以使用: