Python 插入图片到 Excel 指定表单 - 使用 openpyxl 库
Python 插入图片到 Excel 指定表单 - 使用 openpyxl 库
本文将介绍如何使用 Python 的 openpyxl 库,将图片插入到已存在的 Excel 文件中指定的表单(Sheet)内。
原示例代码:
from PIL import Image
from openpyxl import Workbook
from openpyxl.drawing.image import Image as Img
source_image_path = 'C:\1.jpg'
# 插入图片到Excel
excel_file_path = 'C:\Users\Una\Desktop\【Consumer&SMB】Battery Life Test Report Template-20230731.xlsx'
target_cell = 'C24'
wb = Workbook()
ws = wb.active
img = Img(source_image_path)
img.width = img.width // 10
img.height = img.height // 10
ws.add_image(img, target_cell)
wb.save(excel_file_path)
修改后的示例代码:
以下代码将图片插入到名为'Batterylife'的表单内:
from PIL import Image
from openpyxl import load_workbook
from openpyxl.drawing.image import Image as Img
source_image_path = 'C:\1.jpg'
excel_file_path = 'C:\Users\Una\Desktop\【Consumer&SMB】Battery Life Test Report Template-20230731.xlsx'
target_cell = 'C24'
wb = load_workbook(excel_file_path)
ws = wb['Batterylife'] # 获取名为'Batterylife'的表单
img = Img(source_image_path)
img.width = img.width // 10
img.height = img.height // 10
ws.add_image(img, target_cell)
wb.save(excel_file_path)
关键代码说明:
load_workbook: 使用此函数加载已存在的 Excel 文件。wb['Batterylife']: 通过表单名称获取名为'Batterylife'的表单对象。ws.add_image(img, target_cell): 将图片插入到指定表单(ws)的指定单元格(target_cell)。
其他注意事项:
- 使用
img.width // 10和img.height // 10可以调整图片大小。您可以根据需要修改除数。 - 确保已安装
openpyxl库。如果没有,请使用pip install openpyxl进行安装。
希望本教程能够帮助您将图片插入到 Excel 指定表单中。如果您有任何其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/esPz 著作权归作者所有。请勿转载和采集!