Angular 5以自定义格式导出Excel

时间:2019-02-26 10:57:55

标签: angular

我正在使用Angular提供的Excel服务。我想要得到如图所示的输出。必须以这种格式导入Excel。

enter image description here

“我的组件”调用该服务以获取JSON数据,然后调用Excel服务以导出输出。如何自定义函数以获取此输出格式?

JSON格式:

[
    {
        "applicationName": "Application1", 
        "migration": "Rehost", 
        "hostname": "DemoVM5", 
        "ipAddress": "10.0.1.7", 
        "operatingSystem": "Microsoft(R) Windows(R) Server 2003, Standard Edition", 
        "migrationStatus": "Failed", 
        "error": null, 
        "runDetails": {
            "rehostCompletedCount": 0, 
            "rehostFailedCount": 2, 
            "refactorCompletedCount": 0, 
            "refactorFailedCount": 0, 
            "runId": 41, 
            "rehostCount": 2, 
            "refactorCount": 0, 
            "status": null, 
            "dateTime": null
        }
    }, 
    {
        "applicationName": "Application1", 
        "migration": "Rehost", 
        "hostname": "DemoVM2", 
        "ipAddress": "10.0.1.6", 
        "operatingSystem": "Microsoft(R) Windows(R) Server 2003, Standard Edition", 
        "migrationStatus": "Failed", 
        "error": null, 
        "runDetails": {
            "rehostCompletedCount": 0, 
            "rehostFailedCount": 2, 
            "refactorCompletedCount": 0, 
            "refactorFailedCount": 0, 
            "runId": 41, 
            "rehostCount": 2, 
            "refactorCount": 0, 
            "status": null, 
            "dateTime": null
        }
    }
]

Excel服务代码

import {
  Injectable
} from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import * as _ from 'underscore';

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';

@Injectable()
export class ExcelService {
  public data: any;
  public sheetName: string = "Sheet1";
  public workbook: XLSX.WorkBook = {
    Sheets: {},
    SheetNames: [],
    Props: {}
  }
  public ws: any;
  public wbout: any;

  constructor() {}

  public exportAsExcelFile(json: any[], excelFileName: string): void {
    this.data = json;
    this.downloadExcel(excelFileName);
  }

  public transformData(data: any) {
    let dataNew: any = [];
    let keys_arr = [];
    _.each(data, function(json) {
      let key: any = json;
      let arr = _.filter(key, function(val, i) {
        let value: any = val;
        let index: any = i;
        keys_arr.push(index);
        if (value == 0) {
          return '0';
        } else {
          return value;
        }
      });
      dataNew.push(arr);
    });
    dataNew.unshift(_.uniq(keys_arr));
    return dataNew;
  }

  public sheet_from_array_of_arrays(data) {
    let ws = {};
    let endCell = {
      c: 10000000,
      r: 10000000
    };
    let startCell = {
      c: 0,
      r: 0
    };
    let range = {
      s: endCell,
      e: startCell
    };

    let wscols = [];

    for (let R = 0; R != data.length; ++R) {
      for (let C = 0; C != data[R].length; ++C) {
        wscols.push({
          wch: 20
        });
        if (range.s.r > R) range.s.r = R;
        if (range.s.c > C) range.s.c = C;
        if (range.e.r < R) range.e.r = R;
        if (range.e.c < C) range.e.c = C;
        let cell = {
          v: data[R][C],
          t: 's',
          s: {}
        };

        if (R === 0) {
          cell.s = {
            "font": {
              "bold": true,
              "sz": 13,
              "alignment": {
                "horizontal": "center",
                "vertical": "center"
              }
            }
          };
        }

        if (cell.v == null) continue;
        let cell_ref = XLSX.utils.encode_cell({
          c: C,
          r: R
        });
        if (typeof cell.v === 'number')
          cell.t = 'n';
        else if (typeof cell.v === 'boolean')
          cell.t = 'b';
        else
          cell.t = 's';
        ws[cell_ref] = cell;
      }
    }
    ws['!cols'] = wscols;

    if (range.s.c < 10000000)
      ws['!ref'] = XLSX.utils.encode_range(endCell, startCell);

    return ws;
  }

  public generateExcelFile(): any {
    this.ws = this.sheet_from_array_of_arrays(this.transformData(this.data));
    this.workbook.SheetNames = [];
    this.workbook.SheetNames.push(this.sheetName);
    this.workbook.Sheets[this.sheetName] = this.ws;
    this.wbout = XLSX.write(this.workbook, {
      bookType: 'xlsx',
      type: 'binary'
    });
    return this.wbout;
  }

  public createView(s: any): ArrayBuffer {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i)
      view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }

  public downloadExcel(fileName: string): void {
    this.sheetName = fileName + '_export_' + new Date().getTime();
    FileSaver.saveAs(new Blob([this.createView(this.generateExcelFile())], {
      type: "application/octet-stream"
    }), fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  }
}

2 个答案:

答案 0 :(得分:0)

对于XLSX库,如果要在excel中提供任何样式,则需要将其与xlsx样式包一起使用。

XLSX-Style 在这里,您将找到有关如何应用单元格样式的文档。

ExcelJS也是另一个流行且易于使用的客户端excel生成库。该库还提供了比xlsx和xlsx样式更多的样式功能。 您可以参考export to excel in Angular using ExcelJS文章作为参考。

答案 1 :(得分:0)

您可以使用exceljs。这是一个纯开源软件包,而XLSX软件包不是。

使用XLSX自定义Excel工作表是一项专业功能。

sheetjs pro doc

Exceljs是生成xlsx的更好选择

exceljs doc

示例代码

  sheet1.getCell('A1').fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "ff1573f4" },
  };
  sheet1.getCell('A1').border = {
    top: { style: "thin" },
    left: { style: "thin" },
    bottom: { style: "thin" },
    right: { style: "thin" },
  };
  sheet1.getCell('A1').font = {
    name: "",
    family: 4,
    size: 11,
    color: { argb: "ffffffff" },
    underline: false,
    bold: true,
  };