Skip to content
Excel실무 경험

Inserting an Image into an Excel Worksheet with ExcelJS

1 min readWorkMoved from my Tistory blogRead the Korean original

PiTemplate.ts

ts
import ExcelJS from 'exceljs';
import { PiType } from '../types/pi';
import { format } from 'date-fns';
import base64Img from '../../actions/utils/base64Img';

import logoImgURL from '../../assets/images/common/ExcelLogoImg.png';

export default async function piTemplate(piDetail: PiType, language: string) {
  const download = async (workbook: ExcelJS.Workbook, fileName: string) => {
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = fileName + '.xlsx';
    anchor.click();
    window.URL.revokeObjectURL(url);
  };

  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet');
  worksheet.mergeCells('B2 : I2');

  // Insert the image into the Excel worksheet.
  const base64LogoImg = (await base64Img(logoImgURL)) as string;
  const logoImg = workbook.addImage({
    base64: base64LogoImg,
    extension: 'png',
  });
  worksheet.addImage(logoImg, 'B2 : I2'); // Cell range where the image is shown

  const fileName = `LPI_${format(new Date(), 'yyyy-MM-dd')}`;
  download(workbook, fileName); // Errors are handled afterward with then and catch
}

Util / base64Img.ts

ts
export default async function base64Img(imgSrc: string) {
  try {
    const data = await fetch(imgSrc);

    const blob = await data.blob();

    const reader = new FileReader();

    return new Promise((resolve, reject) => {
      reader.readAsDataURL(blob);
      reader.onload = () => {
        const base64data = reader.result;
        resolve(base64data);
      };
    });
  } catch (error) {
    console.error('이미지 로드 중 오류 발생:', error);
    throw error;
  }
}

I use fetch(imgSrc) to get the image.

The fetched image goes into data, and data.blob() turns it into blob data.

I think the reason for turning it into blob data is so that FileReader can read it.

  • #Excel
  • #ExcelJS

More in Work