I am developing a Chrome extension where I need to create an Excel (.xlsx) file that includes embedded images. I am using JavaScript to fetch image data and SheetJS (xlsx) to generate the Excel file. However, I am unable to insert images directly into the Excel cells; they are only being added as links or not included at all.
Page Html :
<img alt="3W 3.7V 1000mA 300lm Led COB Light Module For Bike Diy Work" src="https://cdn.shopify.com/s/files/1/0744/0764/1366/files/WhatsApp_Image_2024-02-27_at_1.02.54_PM-removebg-preview_result.webp?v=1723519244">
Image URL will be fetched from such HTML Element and embed Image against the URL and place that image in the cell of xlsx
Below is the Code with done the Task but run on Node whcih is protected in extension developing what will be the perfect solution for this
const ExcelJS = require("exceljs");
const axios = require("axios");
async function addImageToExcel() {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet("My Sheet");
// Define some sample data
const data = [
{
id: 1,
imageUrl:
"https://cdn.shopify.com/s/files/1/0744/0764/1366/files/1pol100A.webp?v=1717142687",
},
{
id: 2,
imageUrl:
"https://cdn.shopify.com/s/files/1/0744/0764/1366/files/schneider-mcb-63-amp-1-pole-500x500_e4d774d1-8d66-4847-8ce2-d3e948dd6a13.webp?v=1717148962",
},
{
id: 3,
imageUrl:
"https://cdn.shopify.com/s/files/1/0744/0764/1366/files/100ATOMZNTOM7-1254300MCCB100A4POLECIRCUITBREAKERINPAKISTAN1.webp?v=1716651428",
},
{
id: 4,
imageUrl:
"https://cdn.shopify.com/s/files/1/0744/0764/1366/files/s-l300-removebg-preview_result.webp?v=1717755958",
},
];
// Add column definitions
worksheet.columns = [
{ header: "ID", key: "id", width: 10 },
{ header: "Image", key: "image", width: 30 }, // Set width to hold images
];
// Load images and add them to the sheet
for (const item of data) {
const row = worksheet.addRow({ id: item.id });
// Set the height of the row
row.height = 90; // Adjust this value to fit your images
const imageId = workbook.addImage({
buffer: (await axios.get(item.imageUrl, { responseType: "arraybuffer" }))
.data,
extension: "png",
});
worksheet.addImage(imageId, `B${row.number}:B${row.number}`);
}
// Save the workbook
await workbook.xlsx.writeFile("ExcelWithImages.xlsx");
console.log("Excel file with images saved!");
}
addImageToExcel().catch(console.error);