Angular:无法使用 ExcelJS 导出 excel - 错误 TS2307:找不到模块 'stream' - 错误 TS2503:找不到命名空间 'NodeJS'

Angular : Can't export excel using ExcelJS - error TS2307: Cannot find module 'stream' - error TS2503: Cannot find namespace 'NodeJS'

我尝试使用 ExcelJS

导出 excel 文件

这是我在 VS Code 终端中的控制台

ERROR in node_modules/exceljs/index.d.ts:1398:22 - error TS2307: Cannot find module 'stream'.

1398  read(stream: import('stream').Stream): Promise<Workbook>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1424:23 - error TS2307: Cannot find module 'stream'.

1424  write(stream: import('stream').Stream, options?: Partial<XlsxWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1511:22 - error TS2307: Cannot find module 'stream'.

1511  read(stream: import('stream').Stream, options?: Partial<CsvReadOptions>): Promise<Worksheet>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1531:23 - error TS2307: Cannot find module 'stream'.

1531  write(stream: import('stream').Stream, options?: Partial<CsvWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1828:19 - error TS2307: Cannot find module 'stream'.

1828            stream: import('stream').Stream;
                               ~~~~~~~~
node_modules/exceljs/index.d.ts:1872:34 - error TS2503: Cannot find namespace 'NodeJS'.

1872             dictionary: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default                                      ~~~~~~

这里是app.component.html

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> -->

  <!-- serial must : first jquery then popper then bootstrap -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> -->


</head>

<body>

    <div class="row">

      <div class="col-md-2">
        <button class="btn btn-secondary" (click)='downloadExcel()'>Download as Excel</button>
      </div>

    </div>

</body>

</html>

这里是app.component.ts

import { Component } from '@angular/core';
import * as Excel from 'exceljs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'resttest10';

  async downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];

    worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

    // save under export.xlsx
    await workbook.xlsx.writeFile('export.xlsx');

    // load a copy of export.xlsx
    const newWorkbook = new Excel.Workbook();
    await newWorkbook.xlsx.readFile('export.xlsx');

    const newworksheet = newWorkbook.getWorksheet('My Sheet');
    newworksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];
    await newworksheet.addRow({ id: 3, name: 'New Guy', dob: new Date(2000, 1, 1) });

    await newWorkbook.xlsx.writeFile('export2.xlsx');

    console.log('File is written');
  }
}

我不明白为什么它正在寻找流模块(更有趣的是 - 找不到命名空间 'NodeJS' - 我可以 运行 所有其他 angular NodeJS 项目没有错误)

请指出我无法导出的原因excel。

在您的 tsconfig.app.json 文件中添加“类型”:[“节点”]

请注意,“类型”位于 tsconfig 的编译器选项部分。

您不能直接在客户端写入文件。该方法意味着在 nodejs 的后端使用。如果您的期望是在客户端下载此文件。你的代码应该是这样的:-

import { Component } from "@angular/core";
import * as Excel from "exceljs";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "resttest10";

  async downloadExcel() {
    const date = new Date()
      .toISOString()
      .slice(0, 10)
      .split("-")
      .reverse()
      .join("/");
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet("My Sheet");

    worksheet.columns = [
      { header: "Id", key: "id", width: 10 },
      { header: "Name", key: "name", width: 32 },
      { header: "D.O.B.", key: "dob", width: 15 }
    ];

    worksheet.addRow({ id: 1, name: "John Doe", dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: "Jane Doe", dob: new Date(1965, 1, 7) });

    workbook.xlsx.writeBuffer().then((data: any) => {
      console.log("buffer");
      const blob = new Blob([data], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      document.body.appendChild(a);
      a.setAttribute("style", "display: none");
      a.href = url;
      a.download = "export.xlsx";
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    });
  }
}

导入 excel 时:尝试签入 tsconfig.app.json 在预定义代码中添加 "types": ["node"].

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

我找到了解决这个问题的简单方法!

评论或删除导入 import * as Excel from 'exceljs'

现在你可以像这样导入: import * as Excel from 'exceljs/dist/exceljs.min.js'

如果您使用的是angular8及以下版本,您需要安装excelJs 1.12.0版本

step by step to use excejs with angular