SoFunction
Updated on 2025-04-05

Angular Excel import and export implementation code

Preface

This article is based on angular v7.2.7 and was first written on 2019-4-17.

Although the code is based on angular 7.2.7, the syntax is based on angular and all the above can be used. During project development, we often need to interact with the backend file, common ones such as image upload, excel import and export, etc. Here we will only discuss the import and export of excel.

Excel import

Importing excel in angular is actually very simple, you only need to install the xlsx plugin.

Install the xlsx plugin

npm install xlsx --save

Import in component

import * as XLSX from 'xlsx';

Key Code

import * as XLSX from 'xlsx';

excelData = [];

importExcel(evt: any) {
  /* wire up file reader */
  const target: DataTransfer = <DataTransfer>();
  if ( !== 1) throw new Error('Cannot use multiple files');
  const reader: FileReader = new FileReader();
   = (e: any) => {
   /* read workbook */
   const bstr: string = ;
   const wb:  = (bstr, { type: 'binary' });

   /* grab first sheet */
   const wsname: string = [0];
   const ws:  = [wsname];

   /* save data */
    = (.sheet_to_json(ws, { header: 1 }));

    = "" // Clear  };
  ([0]);

 }

Excel export

We generally implement traditional export functions in the backend, and the Url or file stream of the file generated by the backend is given to the frontend. Note: This is downloaded directly through the browser's download function. Generally, there are several ways to implement it:

get request + (url)

The backend returns a file's url or file stream, which can be downloaded directly. The premise is that the http request is get.

post request + <a> tag

Front-end code:

exportExcel(codeList: string[]) {
  return (, codeList, {
   responseType: 'arraybuffer',//Set the response type   observe:"response",//Return to response header   headers: { 'Content-Type': 'application/json' }
  })
   .subscribe((response:any)=&gt;{
    (response, "application/;charset=utf-8")
   })

 }

 /**
  * Method is use to download file.
  * @param data - Array Buffer data
  * @param type - type of the document.
 */
downLoadFile(data: any, type: string) {
   var blob = new Blob([], { type: type});
   let downloadElement = ('a');
   let href = (blob); //Create a download link    = href;
   let filename = ("Download-FileName");//The custom header returned by the backend    = decodeURI(filename); 

   (downloadElement);
   (); //Click to download   (downloadElement); //Download to remove elements   (href); //Release the blob object }

Backend code:

The backend is using Core 2.1

public IActionResult CreateExcel(string fileName,List&lt;ExportProductModel&gt; list)
 {
  string[] propertyNames = {""};//Business code  string[] propertyNameCn = {""};//Business code  MemoryStream ms = ExcelsHelper&lt;ExportProductModel&gt;.ListToExcel(fileName, list, propertyNames, propertyNameCn);
  ("Download-FileName",(fileName));
  return File(ms, "application/;", (fileName));
 }

(options =&gt;
         {
          ("AllowAllOrigin", builder =&gt;
                   {
                    ()
                     .AllowAnyMethod()
                     .AllowAnyOrigin()
                     .AllowCredentials()
                     .WithExposedHeaders("Download-FileName"); 

                   });
         });

Backend code

The key point here is to set a cross-domain response header (that is, "Download-FileName"), and each language has its own implementation method. If not set, the front-end cannot get the response header.

post request + form form + iframe tag (no code implementation yet)

Summarize

I encountered the following problems during the development process and I have been struggling for a long time:

  • The MIME type of the front and back ends does not correspond, resulting in the file being unable to be downloaded successfully. Here isComplete list of MIME types
  • The response header cannot be obtained for two reasons:

(1) The backend does not have a cross-domain response header set

(2) The front-end http request. Syntax writing errors, and the http response body is obtained, rather than the complete http response. For the complete writing method, refer to the above code, the key is: observe:"response"

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.