在Angular 6和ExcelJS中生成的Excel文件不会在使用FileSaver的登台中下载

时间:2019-05-31 14:27:31

标签: angular filesaver.js exceljs

我正在使用 Angular 6.2.9 做一个Web应用程序,并且试图生成一个Excel文件以将其下载到客户端。

"dependencies": {
    "exceljs": "^1.11.0",
    "file-saver": "^2.0.2"
  },
  "devDependencies": {
    "@angular/cli": "~6.2.9"
  }

当我执行ng serve时,文件会正确下载,但是,当我将应用程序上载到暂存区(服务器/生产)时,文件不会下载,并且控制台中也没有任何错误。我的意思是,当您选择一个按钮来生成/下载文件时,什么也没发生。

我发现GitHub上有更多人对此有疑问,我正在遵循GitHub用户的建议,链接为:https://github.com/exceljs/exceljs/issues/511#issuecomment-394337817

我在做

import {Injectable} from '@angular/core';

import * as Excel from 'exceljs/dist/exceljs.min.js';
import * as ExcelProper from 'exceljs';
import * as FileSaver from 'file-saver';

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

@Injectable({
  providedIn: 'root'
})
export class ExcelService {

  workbook: ExcelProper.Workbook;
  worksheet: ExcelProper.Worksheet;

  constructor() {
    // Create workbook and worksheet
    this.workbook = new Excel.Workbook();

    // Set Workbook Properties
    this.workbook.creator = 'Web';
    this.workbook.lastModifiedBy = 'Web';
    this.workbook.created = new Date();
    this.workbook.modified = new Date();
    this.workbook.lastPrinted = new Date();

    // Add a Worksheet
    this.worksheet = this.workbook.addWorksheet('File');
  }

  public generateExcel() {

    // Title
    const title = 'Excel file example';

    // Add Row and formatting
    const titleRow = this.worksheet.addRow([title]);
    titleRow.font = {
      name: 'Arial',
      family: 4,
      size: 16,
      bold: true
    };

    // Add blank Row
    this.worksheet.addRow([]);

    // Generate Excel File
    this.workbook.xlsx.writeBuffer().then((data2) => {
      const blob = new Blob([data2], {type: EXCEL_TYPE});
      // Given name
      FileSaver.saveAs(blob, 'download.xlsx');
    });
  }

}

我尝试过:

// Method 1
this.workbook.xlsx.writeBuffer().then((data2) => {
      const blob = new Blob([data2], {type: EXCEL_TYPE});
      const url = window.URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = 'download.xlsx';
      anchor.click();
      window.URL.revokeObjectURL(url);
    });

// Method 2
this.workbook.xlsx.writeBuffer().then((data2) => {
      const blob = new Blob([data2], {type: EXCEL_TYPE});
      // Given name
      FileSaver.saveAs(blob, 'download.xlsx');
    });

只有当我在本地尝试时,这两种方法才能完美工作。

根据我的建议,我没有在tsconfig.json内添加任何内容,如下所示:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

我的目标是能够下载将应用程序上载到服务器/生产模式时生成的Excel文件。

0 个答案:

没有答案
相关问题