Export data to excel sheets using SheetJS in Angular.

In the previous post we have see how to get started with exporting data to excel files using SheetJS / XLSX library.

Now, let’s try create a service class which takes an array for multiple tables data and export the data to sheets in the excel file.

import { Injectable } from "@angular/core";
import * as XLSX from "xlsx";
import * as _ from "lodash";

/**
 * Service class to export data to multiple sheets in an excel file.
 * ! Please check SheetJS docs and research before using this code.
 */
@Injectable({
  providedIn: "root",
})
export class ExcelDataService {

  /**
   * Takes data and file to export data to excel file.
   * @param data Multiple tables data will be accepted.
   * @param fileName Name of the excel file.
   */
  exportRawDataToExcel(data: any[], fileName: string) {
    if (!data || (data && data.length === 0)) {
      throw new Error("No data to export");
    }
    const wb = XLSX.utils.book_new();
    data.forEach((value, index) => {
      /**
       * Add worksheet to workbook
       */
      XLSX.utils.book_append_sheet(
        wb,
        this.getWorkSheet(value),
        `Sheet ${index}`
      );
    });
    XLSX.writeFile(wb, fileName + ".xlsx");
  }

  // Create the worksheet from the data passes.
  private getWorkSheet(sheetData: any[]) {
    const data = [];
    const merges = [];
    const headers = [];
    const keys: string[] = _.keys(_.head(sheetData));
    let mergeAcrossStartC = 0;
    for (let m = 0; m < keys.length; m++) {
      merges.push({
        s: { r: 0, c: mergeAcrossStartC },
        e: {
          r: 0,
          c: mergeAcrossStartC,
        },
      });
      mergeAcrossStartC = mergeAcrossStartC + 1;
      headers.push(keys[m]);
    }
    data.push(headers);
    for (let j = 0; j < sheetData.length; j++) {
      const rowData = [];
      for (let k = 0; k < keys.length; k++) {
        rowData.push(sheetData[j][keys[k]]);
      }
      data.push(rowData);
    }
    const ws = XLSX.utils.aoa_to_sheet(data);

    ws["!cols"] = [];
    _.forEach(headers, (val) => {
      ws["!cols"].push({ wpx: 120 });
    });
    ws["!merges"] = merges;
    return ws;
  }
}

Above code will be overwhelming, so I would suggest to investigate the SheetJS tool.

Most importantly, we are using XLSX.utils.aoa_to_sheet() to create a new sheet with each of the table data.

Checkout complete code on Github.

Published by Kumar Gandhi K

Hi! I’m Kumar and I live in Bangalore (IN) with my family. By profession I’m a Web Developer experienced in a vast variety of frameworks and technologies, like, HTML, CSS, JavaScript, Angular, Bootstrap… Using these i have built or sometimes maintained mid market and enterprise level applications. I worked for few software companies over the years and on few domains like finance, field-service and storage. I also did consulting job at one point. I am loyal and hard (or for better word smart) working individual. In my free time I read books, in fact I buy a lot of books hoping that some day I might find all the time in the world to read them and I also enjoy watching TV.

Leave a comment