Andrea Mazzarotto
Andrea Mazzarotto

Reputation: 21

ExcelJs with nestJs error: Cannot read properties of undefined (reading 'Workbook')

I'm trying to set up a simple excelService with excelJs in nestJs but setting the the workbook I have this error:

const workbook = new Excel.Workbook(); ^ TypeError: Cannot read properties of undefined (reading 'Workbook')

here's my code:

import { Injectable } from '@nestjs/common';
import { PanelDto } from 'src/panel/dto/panel.dto';
import { PanelService } from 'src/panel/panel.service';
import * as path from 'path';
import Excel from 'exceljs';

@Injectable()
export class ExcelService {

  constructor(private panelService: PanelService) {}

  async createExcel(panelId: number) {
    const panel: PanelDto = await this.panelService.getOnePanelById(panelId);
    const unswers = panel.unswers;

    const workbook = new Excel.Workbook();

    const worksheet = workbook.addWorksheet(
      'Questionaire_' + panel.questionaire.name,
    );

    const worksheet = workbook.addWorksheet(
      'Questionaire_' + panel.questionaire.name,
    );

    const columns: Column[] = [
      { key: 'questionId', header: 'Question ID' },
      { key: 'question', header: 'Question' },
      { key: 'unswerId', header: 'Unswer ID' },
      { key: 'unswer', header: 'Unswer' },
    ];
    worksheet.columns = columns;

    unswers.forEach((u) => {
      const row: RowData = {
        questiondId: u.question.id,
        question: u.question.question,
        unswerId: u.id,
        unswer: u.unswer,
      };
      worksheet.addRow(row);
    });

    const exportPath = path.resolve(__dirname, 'questionaire.xlsx');

    await workbook.xlsx.writeFile(exportPath);
  }
}

interface RowData {
  questiondId: number;
  question: string;
  unswerId: number;
  unswer: string;
}

interface Column {
  key: string;
  header: string;
}

in my package.json I have this: "exceljs": "^4.3.0",

I just expect to create a workbook and adding rows ecc.. What I am missing?

Upvotes: 2

Views: 3822

Answers (2)

Ali Mortazavi
Ali Mortazavi

Reputation: 41

You could have use:

import * as Excel from 'exceljs'

I solved with that

Upvotes: 4

Andrea Mazzarotto
Andrea Mazzarotto

Reputation: 21

ok, I solved by myself changing:

import Excel from 'exceljs';

with:

const ExcelJS = require('exceljs');

as said in the docs but it should be the same?

Upvotes: 0

Related Questions