import base64
import io
import openpyxl
from openpyxl.drawing.image import Image
from openpyxl.utils import units
def process_excel_file(input_file, output_file, base64_col, image_col):
# 加载输入工作簿
wb = openpyxl.load_workbook(input_file)
ws = wb.active # 假设处理的是活动工作表
# 单元格尺寸转换因子
# Excel 列宽单位转换为像素(近似,取决于 DPI 和字体设置)
# 1 单位宽度 ≈ 7 像素(基于默认字体)
# 行高以点为单位,1 点 ≈ 1.333 像素(假设 96 DPI)
pixels_per_width_unit = 7
pixels_per_point = 1.333
# 遍历第 2 到第 6 行(对应 V2 到 V6 单元格)
for row in range(2, 7):
# 获取指定列(例如 'V')中的 base64 字符串
base64_cell = ws[f"{base64_col}{row}"]
base64_string = base64_cell.value
# 检查单元格是否包含有效的 base64 字符串
if base64_string and isinstance(base64_string, str) and base64_string.startswith("data:image/png;base64,"):
try:
# 提取 base64 数据(去除前缀)
base64_data = base64_string.split(",")[1]
# 将 base64 字符串解码为字节
img_data = base64.b64decode(base64_data)
# 创建 BytesIO 对象以存储图像数据
img_io = io.BytesIO(img_data)
# 为 openpyxl 创建 Image 对象
img = Image(img_io)
# 获取目标单元格(例如 AC2)的尺寸
target_cell = f"{image_col}{row}"
col_idx = openpyxl.utils.column_index_from_string(image_col) - 1
# 获取列宽(Excel 单位,默认 8.43 如果未设置)
col_width = ws.column_dimensions[image_col].width or 8.43
# 获取行高(点,默认 12.75 如果未设置)
row_height = ws.row_dimensions[row].height or 12.75
# 将单元格尺寸转换为像素
img_width_pixels = col_width * pixels_per_width_unit
img_height_pixels = row_height * pixels_per_point
# 设置图片尺寸以匹配单元格大小
img.width = img_width_pixels
img.height = img_height_pixels
# 将图片锚定到目标单元格(例如 AC2)
img.anchor = target_cell
# 将图片添加到工作表
ws.add_image(img, target_cell)
except Exception as e:
print(f"处理第 {row} 行图像时出错:{e}")
else:
print(f"{base64_col}{row} 中没有有效的 base64 图像数据")
# 保存输出工作簿
wb.save(output_file)
print(f"Excel 文件成功保存到 {output_file}")
# 示例用法
input_excel = "input.xlsx"
output_excel = "output.xlsx"
base64_col = "V" # V是base64所在列
image_col = "AC" # AC为生成图片所在列
process_excel_file(input_excel, output_excel, base64_col, image_col)
用Python语言把excel内base64文本内容转成图片直接在excel中显示
发表评论