Skip to main content
 首页 » 编程设计

python之我们可以访问和替换 xlsx 中的图像吗

2024年12月31日10kevingrace

我正在编写一个用于自动化流程的脚本,该脚本需要更新 excel 文件,然后根据 Excel 文件中存在的一些数据绘制图表,然后将图表插入同一个 Excel 文件中。 我使用 openpyxl 读取和写入 excel 文件,然后使用 matplotlib 绘制数据图表,然后将图表插入同一个 excel 文件。 Excel 文件中的数据每周更新一到两次。每次更新数据时,我都需要绘制一个更新的图表并将该图表插入 Excel 文件中。现在我的脚本正在自动更新 Excel 文件中的值并为更新的数据绘制图表但是当我插入图表时它不会覆盖之前的图表它每次都将图表附加到之前的图表上方,因此 Excel 文件的大小将不断增加。

现在我用于在 Excel 文件中绘制和插入图表的代码是-

fig = plt.figure(figsize=(8,4))  
PLT = fig.add_axes([0.04, 0.08, 0.79, 0.8])  
 
plt.xlabel("WORKING WEEK (WW)",fontsize=7) 
plt.ylabel("UTILIZATION [%]",fontsize=7) 
plt.title("PATCH UTILIZATION",fontsize=9) 
#PLT.subplots_adjust(right=0.8) 
for i in range(len(p)): 
    PLT.plot(x,p[i],label = '%s'%row[0],marker="s",markersize=2) 
PLT.legend(bbox_to_anchor=(1.21,1),borderaxespad=0,prop={'size':6}) 
PLT.tick_params(axis='both', which='major', labelsize=4) 
plt.savefig("myplot.png",dpi=160) 
wb=load_workbook('Excel.xlsm',read_only=False,keep_vba=True) 
ws=wb['Patch Util'] 
img = openpyxl.drawing.image.Image("myplot.png") 
img.anchor='D50' 
ws.add_image(img) 
wb.save('Excel.xlsm') 

“x”和“p”是两个包含数据的列表(p 是列表的列表),当 Excel 文件中的数据更新时,它们将被更新。

我想要的是绘制一个图形并插入一次。现在,每当数据更新时,我想从 Excel 文件访问相同的图表,为更新的数据绘制它并将其重新插入 Excel 文件,而不是每次都在前一个图表的顶部插入一个新图表,这样大小Excel 文件的大小保持不变。

如果有人能帮助我,那将是很大的帮助

请您参考如下方法:

Comment: No..I am using 2.5.6 version and in my case every graph and chart is retained

显示以下输出:

from openpyxl import load_workbook 
 
wb = load_workbook(<your file path>) 
ws = wb.worksheets[<your sheet index>] 
 
for image in ws._images: 
    print("_id:{}, img.path:{}".format(image._id, image.path)) 

Comment: the output i got is- _id:1, img.path:/xl/media/image1.png


Question: Can we access and replace a image in a xlsx

您可以替换 ws._images 中的 Image 对象。 对于第一次,您必须初始化ref 数据,使用ws.add_image(...) 照常进行。如果图像存在 len(ws._images) == 1,您可以将其替换为新的 Image 对象。
例如:

if len(ws._images) == 0: 
    # Initalise the `ref` data, do ws.add_image(...)    
    img = openpyxl.drawing.image.Image("myplot.png") 
    img.anchor='D50' 
    ws.add_image(img) 
 
elif len(ws._images) == 1: 
    # Replace the first image do **only** the following: 
    ws._images[0] = openpyxl.drawing.image.Image("myplot.png") 
    # Update the default anchor `A1` to your needs 
    ws._images[0].anchor='D50' 
else: 
    raise(ValueError, "Found more than 1 Image!") 

Note: You are using a class private property, this could result in unexpected side effect.

使用 openpyxl 版本 2.5.6