Nwp _
Nwp _

Reputation: 63

worksheet.addChart is not a function

I'm using FeathersJS and want to export an Excel chart using exceljs, but it gives an error 'worksheet.addChart is not a function.' What should I do? This is my code, which receives JSON to create an Excel file and includes style settings.

async create(data, params) {
    console.log(data);
    const { filename } = data;

    const workbook = new ExcelJS.Workbook();

    // Iterate over each sheet in the data object
    for (const sheetName in data) {
      if (sheetName !== 'filename') {
        const sheetData = data[sheetName];
        const worksheet = workbook.addWorksheet(sheetName);

        // Add chart if specified
        if (sheetData.chart) {
          const chartSheet = workbook.addWorksheet('Chart');
          const chart = chartSheet.addChart({
            name: sheetName,
            title: sheetData.chart.title,
            ref: 'A1:B4', 
            rows: [
              { cell: 'A1', label: 'Name' },
              { cell: 'B1', label: 'Value' },
              ...sheetData.chart.map((item, index) => ({ cell: `A${index + 2}`, label: item.name })),
              ...sheetData.chart.map((item, index) => ({ cell: `B${index + 2}`, label: item.value })),
            ],
            chart: 'bar',
          });

          // Set the size and position of the chart
          chartSheet.addImage(chart, {
            tl: { col: 5, row: 1 },
            br: { col: 15, row: 20 },
          });
        }
      }
    }

    // Save the Excel file
    const filePath = `./public/${filename}.xlsx`;
    await workbook.xlsx.writeFile(filePath);

    // Return the file path
    return { path: filePath };
  }

Upvotes: 2

Views: 150

Answers (0)

Related Questions