1. Install the XLSX plug-in

cnpm install xlsx -S
// or
yarn add xlsx -D
Copy the code

2. Encapsulate servicesexcel.service.ts

import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';
const excel = {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'.extension: 'csv'.fileAccept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'};// Default configuration item
let CONFIG: XLSX.Sheet2JSONOpts = {
  defval: ' '.// Null defaults to ''
  raw: false.// Whether to format
  blankrows: false  // Ignore blank lines
};

export abstract class ExcelModel {
  abstract export(json: any[].fileName: string) :void;
  abstract read(file: Blob): Promise<any>;
}

@Injectable({
  providedIn: 'root'
})
export class ExcelService extends ExcelModel {
  constructor() {
    super(a); }export(json: any[].fileName: string) :void {
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, fileName);
    const fullName = `${fileName}_export_The ${new Date().getTime()}.${excel.extension}`;
    XLSX.writeFile(workbook, fullName);
  }
  / * * *@description: Read excel files *@param File blob type *@param Config Sets the format for reading Excel files, xlsx. Sheet2JSONOpts */read(file: Blob | File, config? : XLSX.Sheet2JSONOpts):Promise<any> {
    if (config) {
      CONFIG = Object.assign(CONFIG, config); // Customize the configuration item
    }
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    // const JSON_OBJ = {};
    return new Promise((resolve) = > {
      reader.onload = () = > {
        const data = reader.result;
        const workbook = XLSX.read(data, { type: 'binary' });
        // Only one sheet is read
        workbook.SheetNames.forEach((sheetName) = > {
          const XL_ROW_OBJECT = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], CONFIG);
          resolve(XL_ROW_OBJECT); // The first sheet will be passed only once}); }; }); }}Copy the code

3 the use of

<input type="file" (change) ="importFile($event)" />
Copy the code
 async importFile(e: Event) {
    const f = e.target as HTMLInputElement;
    const file = f.files[0];
    f.value = ' '; // The same file cannot be uploaded
    const type = file.name.split('. ') [1];
    if (type! = ='xls' && type! = ='xlsx' && type! = ='csv') {
      this.msg.error('Please upload file in specified format');
      return;
    }
    // Read the file
    let result = await this.excel.read(file, { header: ['label'.'number']});
    if (result[0].label ! = ='tags' || result[0].number ! = ='Subscriber number') {
      this.msg.error('Table header does not correspond, please download template file to write');
      return;
    }
    console.log(result);
  }
Copy the code

Try importing an Excel

Look at the print