Skip to content

How to locate multiple floating images in a cell so that they do not overlap and are not compressed #28

@dxxdx

Description

@dxxdx

//使用vue3+ts+vite,但是在添加图片,设置ext就会重叠,要么就会压缩
const E1 = async () => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet("产品清单");
// 添加表头和数据
worksheet.columns = [
{ header: "产品ID", key: "id", width: 10 },
{ header: "产品名称", key: "name", width: 20 },
{ header: "产品图片", key: "images", width: 30 },
];

worksheet.addRow({ id: 1, name: "高端笔记本电脑" }).height = 80;

// 准备多张图片URL
const imageUrls = [
"https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
"https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg",
"https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg",
];

// 添加多张浮动图片到B2单元格上方
for (let i = 0; i < imageUrls.length; i++) {
const response = await fetch(imageUrls[i]);
const buffer = await response.arrayBuffer();
const imageId = workbook.addImage({
buffer: buffer,
extension: imageUrls[i].split(".").pop() as "png" | "jpeg",
});

// const colWidth = worksheet.getColumn(3).width; // 获取列宽(字符单位)
// const percent = 0.3; // 30%
// console.info(colWidth,"colWidth")

// 每张图片偏移位置,避免完全重叠
worksheet.addImage(imageId, {
  // tl: { col: 2, row: 1, },// 左上角位置
  // ext: { width: 80, height: 80 }, // 像素大小
  tl: {
    col: 2 + 0.3 * i,
    row: 1,
  },
  br: {
    col: 2.3 + 0.3 * i,
    row: 2,
  },
  editAs: "oneCell" as const,
});

}

// 导出Excel
const buffer = await workbook.xlsx.writeBuffer();
saveAs(new Blob([buffer]), "products_with_multiple_images.xlsx");
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions