Issue exporting excel file in Angular using ExcelJS: encountering error TS2307 stating "Cannot find module 'stream'" and error TS2503 indicating "Cannot find namespace 'NodeJS'"

Exporting an excel file using ExcelJS has been a challenge for me.

When I checked my console in the VS Code terminal, I encountered the following errors:

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'.
...

Here is the content of 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">

...

</body>

</html>

And here is the code from 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() {

    // Code for exporting excel

  }
}

I'm puzzled by the fact that it's looking for the stream module (and even more oddly - "Cannot find namespace 'NodeJS'" - despite being able to run other Angular NodeJS projects without issues).

If anyone could shed some light on why I can't export the excel file successfully, I would greatly appreciate it.

Answer №1

To enhance your tsconfig.app.json file, include the following line: "types": ["node"]

Remember, the "types" should be placed within the compilerOptions section of the tsconfig.

Answer №2

It is not possible to directly write a file on the client-side. This method is typically used on the backend side with nodejs. If you wish to download a file on the client-side, your code should look like this:

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();
    });
  }
}

Answer №3

After some trial and error, I discovered a straightforward solution!

If you want to address the issue, consider commenting out or deleting the line of code that reads import * as Excel from 'exceljs'

Instead, try importing it in this manner:

import * as Excel from 'exceljs/dist/exceljs.min.js'

Answer №4

When importing the excel file, make sure to check the tsconfig.app.json for any pre-defined code. In the code snippet, remember to include "types": ["node"].

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

Answer №5

In case you are working with angular 8 or earlier versions, make sure to install excelJs version 1.12.0 for proper functionality.

For detailed instructions on how to utilize excejs with angular, please refer to this guide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to loop through the JSON objects saved in an array of JSON data in local storage

I have reviewed various resources, including Iterate through nested json object array, but none of them seem to address my specific situation. The current challenge I am facing involves storing multiple JSON objects in an array within local storage. This ...

Transforming Backbone JSON data into a template for display

Yesterday, I asked a question that was very helpful to me. I have rewritten most of the code by following tutorials, YouTube videos, and seeking help on Stack Overflow. However, I am unsure of what I am doing wrong when trying to push the JSON data to the ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

The jQuery scrollTop feature seems to be malfunctioning

My code is causing an error that I don't understand. Any help would be appreciated... I'm getting the following error message: Property does not exist on type '.js--section-plan'.ts(2339) when I hover over the offset() in vscode $(&apos ...

Remove items from an array using other items from another array as the index

Let's consider the following scenario: let arr1 = [0,2] // This array is always sorted Just to clarify, these elements in the "arr1" array represent indexes that need to be removed from another array. We also have another array: let arrOvj = [1,4,6, ...

Delay with Vue.js v-bind causing form submission to occur before the value is updated

Trying to update a hidden input with a value from a SweetAlert modal, but encountering issues. The following code isn't working as expected - the form submits, but the hidden field's value remains null. HTML: <input type="hidden" name="inpu ...

Update the image source when hovering over the parent element

Check out this snippet of HTML code: <div class="custom text-center threeBox ofsted"> <a class="ofsted" title="ofsted report" href="http://reports.ofsted.gov.uk/"> <img class="text-center ofstedLogo" src="images/ofsted_good_transparen ...

The onkey_Up function in the HTML textbox is not properly functioning within the ascx control

I attempted to use onkey_up to transfer data from one textbox to another on a user control ascx file, but it is not working when I run it. Could the issue be that I placed the onkey_up function in .ascx instead of the master page? function sync() { ...

AngularJS encountered an error: myFunc has not been defined

I came across a code snippet similar to this one in a Github project, and it seems to be functioning properly. function myFunc($par1, $par2) { //some logic here } angular .module('myApp') .config(['$par1', '$par2' ...

The URL cannot be retrieved using an Ajax call, but it is accessible through Postman

I'm having trouble fetching the URL "" using $.get. Strangely, when I paste the exact same URL into Postman, it works perfectly. Visit my JSFiddle page for reference. $.get( "https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/album", ...

Refreshing Dropotron Data with jQuery

I'm struggling to find a solution for refreshing the <ul> and <li> elements after the page has already loaded. My <li> element is updated with Ajax data, but despite using jQuery to manipulate the DOM, the changes are not reflected ...

Running the Luis Recogniser on ChoicePrompt is a straightforward process that can be easily

In my scenario, I am utilizing a ChoicePrompt which presents the user with two options to choose from. [ { value: 'credit', synonyms: ['titanium', 'world', 'credit', 'mastercard'], } ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...

Steps to open a webpage with a URL that includes #tags=green, pink, and white at the conclusion

Here's the challenge - Open your page with a URL that includes #tags=green,pink,white at the end Create a JavaScript script that extracts the tags from the URL and displays them in a list, with each tag as a separate list item. For instance, if the ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

The use of the keyword 'await' was not anticipated

I'm currently working on a react-native application and I've encountered an issue with my forEach iteration. I decided to use await to pause for the result, but instead I keep receiving an error message stating "Unexpected reserved word 'awa ...

Invoke a React component within a conditional statement

There is a function for exporting data in either csv or xls format based on an argument specifying the type. The functionality works flawlessly for xls but encounters issues with csv. Here's the code snippet: const exportFile = (exportType) => { ...

Is NodeJS primarily used as a socket library for network communication?

Here is a server program written in C language using socket functionality provided by libC # include <unistd.h> # include <sys/socket.h> # include <sys/types.h> # include <string.h> #include <netinet/in.h> main(){ int listfd ...

What is the most effective method for detecting the conclusion of a wheel event in JavaScript?

Is there a way to trigger an event once my wheel event has finished? I came across a solution that uses a scroll event (which is similar) with a setTimeout function here: However, I'm curious if there's a more elegant method to detect when my w ...

"Encountering an issue with Express.json where it fails to parse the

Receiving JSON POST data from an IoT API that includes multipart form-data. Occasionally, an image file may be included but I only want to focus on the JSON part: POST { host: '192.168.78.243:3000', accept: '*/*', 'content-le ...