首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 5以自定义格式导出Excel

Angular 5以自定义格式导出Excel
EN

Stack Overflow用户
提问于 2019-02-26 18:57:55
回答 2查看 4.8K关注 0票数 1

我使用的是Angular提供的Excel服务。我希望得到如下图所示的输出。此格式需要导入Excel。

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

JSON格式:

代码语言:javascript
复制
[
    {
        "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服务代码

代码语言:javascript
复制
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);
  }
}
EN

回答 2

Stack Overflow用户

发布于 2019-02-26 19:24:35

对于XLSX库,如果你想在excel中提供任何样式,你需要在xlsx-style包中使用它。

XLSX-Style在这里你可以找到关于如何应用单元格样式的文档。

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

票数 1
EN

Stack Overflow用户

发布于 2019-02-27 21:31:27

您可以使用exceljs。它是一个纯粹的开源包,而XLSX包不是。

使用XLSX定制excel表格是一种专业的特性。

sheetjs pro doc

Exceljs是生成xlsx的更好选择。

exceljs doc

示例代码:

代码语言:javascript
复制
  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,
  };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54883924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档