首页 > 其他分享 >前端必读3.0:如何在 Angular 中使用SpreadJS实现导入和导出 Excel 文件

前端必读3.0:如何在 Angular 中使用SpreadJS实现导入和导出 Excel 文件

时间:2022-09-23 17:16:31浏览次数:82  
标签:blue SpreadJS text Excel foreColor 3.0 Test sheet

在之前的文章中,我们为大家分别详细介绍了在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/

标签:blue,SpreadJS,text,Excel,foreColor,3.0,Test,sheet
From: https://www.cnblogs.com/powertoolsteam/p/16723385.html

相关文章

  • 【C#】iTextSharps.dll操作Excel、PDF
    一、PDFusingiTextSharp.text;usingiTextSharp.text.pdf;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Tex......
  • df.to_excel()
     df.to_excel()函数将DataFrame导出到excel文件。要将单个对象写入excel文件,我们必须指定目标文件名。如果要写入多个工作表,则需要使用目标文件名创建一个ExcelWrit......
  • 导出excel数据报错Could not find acceptable representation
    org.springframework.web.HttpMediaTypeNotAcceptableException:Couldnotfindacceptablerepresentation 在导出excel数据时,返回的数据时文件流的格式,写入到response......
  • Excel设置格式后必须双击才生效问题的解决办法
    如下:Excel设置了格式后,往往需要双击一下单元才能生效,如果行数较多,谁很麻烦的。解决办法如下:1、选中该列数据;2、数据--分列--分隔符--下一步--Tab键--常规--完......
  • R语言学习丨数据存储文件格式知识,CSV,EXCEL,XML,JSON,MYSQL等
    今天笔记的主要学习内容是R语言里文件相关知识,包含CSV、Excel、XML、JSON、MySQL等。CSV文件基本介绍CSV(Comma-SeparatedValues,字符分隔值,分隔字符也可以不是逗号)是......
  • Python复制Excel表格图片
    importosimporttimeimportpyautoguiimportwin32com.clientaswin32#发送函数deffz(app,bk):x,y=pyautogui.size()time.sleep(1)app.Application.Run......
  • java实现设置Excel下拉框
    在使用Excel的时候用到了下拉框,实现的效果如下↓   在生成excel文件时,需要根据给出的下拉框选项列表动态生成下拉框。实现代码如下:privatevoidcreateSelect(XSS......
  • excel导出大数据量时服务器cpu过高tomcat卡死问题排查
      最近发现一套线上生产系统每周一都会出现宕机的现象,CPU很高,持续几分钟后tomcat直接卡死,系统无法登陆刷新无反应,重启后又回复正常,各种定位各种检查。最开始想到的是不是......
  • delphi TMS FlexCel 导出HTML
    TMSFlexCel导出HTML属性和方法TFlexCelHtmlExport用于将Excel文件导出为HTML的组件。unitFlexCel.RenderTFlexCelHtmlExport.CreateconstructorCreate(const......
  • 前端 excel 表格导出
    传统的表格导出是直接获取数据,传表头,数据,自动下载表格。Blob.js和 Export2Excel.js 如果要导出这样的表格,那么需要重新写一个方法,核心在于  {s:{r:行开始,c:列......