Generating Excel Files with Image Using ExcelJS

The ExcelJS library allows us to add an image to an EXCEL file. Using the code below, we can create an Excel file in the.xlsx format that is compatible with Microsoft Office.

let logoUrl = 'https://xxxx.app.netsuite.com/core/media/media.nl?id=1234&c=6471'
let workbook = new ExcelJS.Workbook();
                let worksheet = workbook.addWorksheet('P&F Global Pricelist');

                // Set Company logo
                let response = https.get({ url: logoUrl  });
                if (response.code === 200) {
                    let base64Data = 'data:image/png;base64,' + response.body.toString('base64');
                    let image = workbook.addImage({ base64: base64Data, extension: 'png' });
                    worksheet.addImage(image, {
                        tl: { col: 0, row: 0 },
                        br: { col: 1, row: 9 },
                    });
                }
 
workbook.xlsx.writeBuffer().then((data) => {
                    let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                    let url = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    a.click();
                    window.URL.revokeObjectURL(url);
                }).catch((error) => {
                    console.error('Error generating Excel file:', error);
                    alert('Error while generating Excel file. Please contact admin.');
                });

The initial segment of the code involves fetching a company logo from a specified URL using an HTTPS request. The codes proceed to convert the logo into a base64-encoded format. This encoded image is then added to the worksheet using the ExcelJS library’s functionality. The positioning of the image within the worksheet is specified by setting coordinates for the top left (tl) and bottom right (br) corners. This step ensures that the company logo is seamlessly integrated into the Excel file.

After incorporating the company logo, the code proceeds to write the entire Excel workbook into a buffer. This buffer is then transformed into a Blob (Binary Large Object), which encapsulates the spreadsheet data. To facilitate user download, a temporary URL is generated using window.URL.createObjectURL. Subsequently, a dynamically created anchor element (<a>) is utilized to simulate a download link. The anchor’s href attribute is set to the Blob’s URL, and the desired filename is specified. Triggering a click on this anchor element initiates the download process, allowing users to obtain the Excel file seamlessly.

Leave a comment

Your email address will not be published. Required fields are marked *