纯前端导出Excel,并在excel添加图片

  • 使用exceljs进行导出

    • 在项目中引入exceljs(下方带了exceljs文档地址)

      npm install exceljs
      
    • 进行使用

import * as ExcelJS from "exceljs";
import { urlToBase64 } from "@/utils/image";

export const exportDetail = {
  methods: {
    async exportExcel(direction) {
      // 定义数据
      let data = this.quantity.getData();
      data.pop()
      const header = [
        ['附件1'],
        ['name'],
        ['标题'],
        ['分包名称:', this.tableInfo.supplierContractName,  '合同编号:',this.tableInfo.supplierContractNo, '计量时段:',this.tableInfo.measurementPeriod, "计量期数:第" + this.tableInfo.measurementNums + "期" ],
        ['扣款单自编号', '扣款事由', '发生日期', '本期扣款金额','备注', '' ]
      ]
      data = header.concat(data)
      data.push(['', '', '', '', '',' ', '' ])
      data.push(['', '上期累计',this.previousDeduction, '本期扣款', this.currentDeduction,' 本期累计',  this.currentDeduction + this.previousDeduction ])
      data.push(['', '', '', '', '',' 负责人', this.tableInfo.submitter, ])

      // 创建Excel工作簿
      const workbook = new ExcelJS.Workbook();

      // 创建工作表
      const worksheet = workbook.addWorksheet("sheet1");//sheet名

      // 设置列宽
      worksheet.columns = [
        { width: 20 },
        { width: 40 },
        { width: 20 },
        { width: 20 },
        { width: 20 },
        { width: 20 },
        { width: 30 },
      ];

      // // 设置合并单元格
      // worksheet.mergeCells("A1:G1");

      // // 设置表头样式
      // const headerRow = worksheet.getRow(1);
      // headerRow.font = { bold: true };
      // headerRow.alignment = { vertical: "middle", horizontal: "center" };

      // 设置数据行
      for (let i = 0; i < data.length; i++) {
        const row = worksheet.addRow(data[i]);
        // 设置行高
        row.height = 30;
        // 设置样式
        row.alignment = { vertical: "middle", horizontal: "center" };
      }
      // 将图片转换为base64
      if(this.tableInfo.signUrl){
          const base64Image = await urlToBase64('https://' + this.tableInfo.signUrl);
          //this.tableInfo.signUrl 从后端获取到的图片地址
            // 插入图片
            const signImage = workbook.addImage({
              base64: base64Image,
              extension: "png",
            });

        worksheet.addImage(signImage, `G${data.length}:G${data.length}`);
      }
      //若要添加多个图片
      //const positionImageRanges = {
       //   projectHeader: "C22:D22", 
        //  projectManager: "F22:G22", 
        //  commerceManager: "C23:D23", 
       // };

      //  const insertImageByPosition = async (worksheet, person, position) => {
      //    if (person[position]) {
            // 插入图片
     //       if(person[position + "Url"]){
     //         const positionImage = await urlToBase64(`https://${person[position + "Url"]}`);
     //         const signImage = workbook.addImage({
     //         base64: positionImage,
     //         extension: "png",
     //         });
      //        worksheet.addImage(signImage, positionImageRanges[position]);
     //       }
            
     //     }
     //   };

        // 调用插入图片函数
    //    await insertImageByPosition(worksheet, person, "produceHeader");
     //   await insertImageByPosition(worksheet, person, "projectHeader");
    //    await insertImageByPosition(worksheet, person, "projectManager");
      

      // 在数据创建完成后再进行单元格的合并,否则会在数据之前插入空值
      worksheet.mergeCells("A2:G2");
      worksheet.mergeCells("A3:G3");
      // 将Excel文件写入文件或导出
      // 导出xlsx文件
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        saveAs(blob, "表名.xlsx");//导出的表名
      });
    },
  },
};

  • image.js

    export function urlToBase64(url) {
      return new Promise((resolve, reject) => {
        var canvas = document.createElement('CANVAS'),
            ctx = canvas.getContext('2d'),
            img = new Image;
        img.crossOrigin = 'Anonymous';
        img.onload = function(){
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img,0,0);
            var dataURL = canvas.toDataURL('image/png');
            resolve(dataURL);
            canvas = null; 
        };
        img.src = url;
      });
    }
    
  • exceljs中文文档地址:https://github.com/exceljs/exceljs/blob/master/README_zh.md

Logo

前往低代码交流专区

更多推荐