Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How To Export Data to Excel in Angular
Oleg Chursin
Oleg Chursin

Posted on

     

How To Export Data to Excel in Angular

Data export to Excel is a common task in modern business-facing apps and of course we have npm packages to help us do just that. An amazing one to consider isAngular Material Table Exporter. But there are a big prerequisite to use it. Your data has to be rendered using Material Table. If you are OK with it, then follow the docs for the mat-table-exporter package for a painless integration - it works like a charm. One gotcha that you may face is the bundle size. If you follow the default integration steps and addMatTableExporterModule toshared.module.ts, your bundle size may gain 1.5Mb. Of course you can lazy-load it, move to the server completely, or use the method below.

Meet excel-export Service

We will be using only one fairly low-level dependency -xlsx and go from there. Let’s make sure we have the latter installed:

npm i xlsx
Enter fullscreen modeExit fullscreen mode

Now we have access to a plethora of methods and options provided by this awesome package which will be integrated intoexcel-export.service.ts.

TLDR: Here’s what the service looks like:

// excel-export.service.tsimport{utilsasXLSXUtils,writeFile}from'xlsx';import{WorkBook,WorkSheet}from'xlsx/types';import{Injectable}from'@angular/core';exportinterfaceIExportAsExcelProps{readonlydata:any[];readonlyfileName:string;readonlysheetName?:string;readonlyheader?:string[];readonlytable?:HTMLElement;}@Injectable({providedIn:'root'})exportclassExcelExportService{fileExtension='.xlsx';publicexportAsExcel({data,fileName,sheetName='Data',header=[],table}:IExportAsExcelProps):void{letwb:WorkBook;if(table){wb=XLSXUtils.table_to_book(table);}else{constws:WorkSheet=XLSXUtils.json_to_sheet(data,{header});wb=XLSXUtils.book_new();XLSXUtils.book_append_sheet(wb,ws,sheetName);}writeFile(wb,`${fileName}${this.fileExtension}`);}}
Enter fullscreen modeExit fullscreen mode

What’s going on above?

First, official xlsx docs tell you to import everything fromxlsx:

import*asXLSXfrom'xlsx';
Enter fullscreen modeExit fullscreen mode

It works, but my personal preference is to import individual methods, interfaces, types, and not pull the whole library along. Hence the adjusted import declarations:

import{utilsasXLSXUtils,writeFile}from'xlsx';import{WorkBook,WorkSheet}from'xlsx/types';
Enter fullscreen modeExit fullscreen mode

We will have only one public methodexportAsExcel that takes the following props:data, fileName, sheetName, header, table with the following interface:

exportinterfaceIExportAsExcelProps{readonlydata:any[];readonlyfileName:string;readonlysheetName?:string;readonlyheader?:string[];readonlytable?:HTMLElement;}
Enter fullscreen modeExit fullscreen mode

Thedata has to be in JSON format to makejson_to_sheet util method happy. Read more about it in the docs:json_to_sheet

If you prefer to grab the DOM’s<table> Element and convert its contents into Excel doc, just pass the desired HTMLElement through and our service will usetable_to_book method. More info on that in the docs:table_to_book

Well,fileName andsheetName are self-explanatory, se we are left with the last optional prop:header.

This is an array of keys from your data Object that controls the column order. If you don’t explicitly pass it, xlsx defaults toObject.keys. Read more onheader:https://github.com/SheetJS/sheetjs#array-of-objects-input

I believe this is all. Just massage the data you want to send down or play with the<table> contents and you have a workingExport as Excel service you can call whenever you need it.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
patelatit53 profile image
Atit Patel
Frontend Consultant who love to write and explore about JavaScript,TypeScript,Angular. #JavaScript #angular #frontend #TypeScript #DEVCommunity #100DaysOfCode
  • Location
    Toronto, Canada
  • Work
    Senior Consultant
  • Joined

Is it possible to export dropdown with the options in excel?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Lead Software Engineer at Aon Cyber Solutions (NYC). Pixel manipulator with passion for UX/UI.
  • Location
    New York City
  • Work
    Senior Software Developer at Aon Cyber Solutions
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp