【问题标题】:Angular : Can't export excel using ExcelJS - error TS2307: Cannot find module 'stream' - error TS2503: Cannot find namespace 'NodeJS'Angular:无法使用 ExcelJS 导出 excel-错误 TS2307:找不到模块“流”-错误 TS2503:找不到命名空间“NodeJS”
【发布时间】:2020-06-01 07:27:44
【问题描述】:

我尝试使用 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' - 我可以运行所有其他有角度的 NodeJS 项目而不会出错)

请指出为什么我不能导出excel。

【问题讨论】:

    标签: javascript angular typescript export-to-excel exceljs


    【解决方案1】:

    在您的 tsconfig.app.json 文件中添加 "types": ["node"]

    请注意,“类型”位于 tsconfig 的 compilerOptions 部分中。

    【讨论】:

    • 我做到了。没有变化
    • +1 用于解决我以前的状态,现在终于 angular 在相同的代码上运行,但仍然无法保存文件 //core.js:6228 错误错误:未捕获(承诺):TypeError : a.createWriteStream is not a function TypeError: a.createWriteStream is not a function//
    【解决方案2】:

    您不能直接在客户端写入文件。该方法意味着在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();
        });
      }
    }
    

    【讨论】:

    • 我猜它比我的版本好,但它会生成一个新错误 TypeError: a.createWriteStream is not a function TypeError: a.createWriteStream is not a function at e.value (exceljs.min.js :3) 在 AppComponent. (app.component.ts:31) 但是,在第 31 行,等待 workbook.xlsx.writeFile('export.xlsx');似乎由于某种原因它没有执行 (paste.ubuntu.com/p/dc83RdDmPJ)
    • 我没有使用 writeFile,你仔细看了吗?我正在使用 writeBuffer。 writeFile 仅适用于后端。
    • 哦,我现在明白了,请编辑您的答案删除我猜的那些行 // 保存在 export.xlsx 下 await workbook.xlsx.writeFile('export.xlsx');当我只使用 writeBuffer 时,一切都很好。
    • 如果解决了您的问题,请将其标记为答案。
    • @piupaul 3.9.0 exceljs
    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      导入 excel 时:尝试检查 tsconfig.app.json 在预定义代码中添加“类型”:[“节点”]。

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

      【讨论】:

      • 这似乎与现有 anwser 重复。
      【解决方案5】:

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

      step by step to use excejs with angular

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-03
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 2017-01-06
        • 1970-01-01
        相关资源
        最近更新 更多