Python: 在Excel中插入图片作为附件 - 使用openpyxl库
使用Python的openpyxl库可以方便地在Excel表格中插入图片作为附件。
步骤:
-
安装库:
pip install openpyxl pip install pillow -
读取Excel文件:
from openpyxl import load_workbook from openpyxl.drawing.image import Image # 打开Excel文件 excel_file_path = r'D:\STRESSTOOL\GPU_Caps_Viewer\benchmark\2023 acer video performance_test_criteria_V1.0_20220928.xls' wb = load_workbook(excel_file_path) # 选择特定的工作表 sheet_name = 'Benchmark Tool' ws = wb[sheet_name] -
读取图片文件:
# 读取图像文件 image_file_path = r'D:\STRESSTOOL\GPU_Caps_Viewer\benchmark\GL 2.1_Furry Cube.png' img = Image(image_file_path) -
插入图片:
# 将图像插入到指定的单元格 cell_coordinate = 'G7' ws.add_image(img, cell_coordinate) -
保存修改:
# 保存修改后的Excel文件 wb.save(excel_file_path)
代码示例:
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
# 打开Excel文件
excel_file_path = r'D:\STRESSTOOL\GPU_Caps_Viewer\benchmark\2023 acer video performance_test_criteria_V1.0_20220928.xls'
wb = load_workbook(excel_file_path)
# 选择特定的工作表
sheet_name = 'Benchmark Tool'
ws = wb[sheet_name]
# 读取图像文件
image_file_path = r'D:\STRESSTOOL\GPU_Caps_Viewer\benchmark\GL 2.1_Furry Cube.png'
img = Image(image_file_path)
# 将图像插入到指定的单元格
cell_coordinate = 'G7'
ws.add_image(img, cell_coordinate)
# 保存修改后的Excel文件
wb.save(excel_file_path)
注意:
- 请确保文件路径的正确性,并将其替换为你实际的文件路径。
- 代码将把图像插入到Excel文件的特定单元格(7, 7)中。
- 为了方便使用,代码中已经将双引号替换为单引号。
希望这个示例代码能够帮助你完成将图片文件插入到Excel表格的任务。
原文地址: https://www.cveoy.top/t/topic/qmwd 著作权归作者所有。请勿转载和采集!