Export excel sheet with logo on top to achieve it on angular version 17?

30 Views Asked by At

I would like to implement the excel export in angular with company logo at the top of the sheet incorporate it, But I couldn't get the logo on excel sheet.

My implementation shown below:

    import { Component } from '@angular/core';
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-export',
  templateUrl: './export.component.html',
  styleUrls: ['./export.component.css']
})
export class ExportComponent {

  constructor() { }

  exportToExcel(): void {
    // Sample data
    const data: any[] = [
      ['Name', 'Age'],
      ['John Doe', 30],
      ['Jane Smith', 25]
    ];

    const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(data);

    // Add logo
    const logo = new Image();
    logo.src = 'path_to_your_logo'; // Replace 'path_to_your_logo' with the actual path of your logo
    const logoBase64 = this.getBase64Image(logo);

    ws['!drawings'] = [
      {
        anchor: {
          type: 'twoCellAnchor',
          from: { col: 0, colOff: '0px', row: 0, rowOff: '0px' },
          to: { col: 1, colOff: '200px', row: 1, rowOff: '200px' }
        },
        graphicFrame: {
          graphic: {
            nvGraphicFramePr: {
              cxnSpPr: {
                graphicFrameLocks: { noChangeAspect: true }
              }
            },
            graphicData: {
              pic: {
                nvPicPr: {
                  cNvPr: { id: 1, name: 'Picture 1', descr: 'logo' },
                  cNvPicPr: { picLocks: { noChangeAspect: true } }
                },
                blipFill: {
                  blip: { $: { 'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' }, $1: { 'r:embed': logoBase64 } },
                  stretch: { fillRect: {} }
                },
                spPr: { prstGeom: { prst: 'rect', avLst: {} } }
              }
            }
          }
        }
      }
    ];

    // Create a new workbook
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // Save the Excel file
    XLSX.writeFile(wb, 'export.xlsx');
  }

  private getBase64Image(img: HTMLImageElement): string {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;

    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);

    return canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
  }
}

I am using the conversion of png format image into an base64 conversion would help to render the image on the excel sheet. Any help would really appreciate it. Thank you.

0

There are 0 best solutions below