将图像粘贴到带有图像的电子表格上时,Excel文件会损坏



问题:使用python将图像添加到excel中。当第一次在空白excel文件上运行代码时,代码运行良好,图像粘贴到电子表格上没有任何问题。第二次运行完全相同的代码时,excel文件损坏。

当已经有图像时,将图像粘贴到电子表格上似乎是个问题。

这是代码:图片:test1.png,test2.png

import os
import openpyxl

print(os.getcwd())
file_name = 'a.xlsx'
wb = openpyxl.load_workbook(file_name)   # open exist excel file
ws = wb["Sheet1"]  # set the active sheet
sheet = wb.active
ws['a2'].value = 11112
wb.save(file_name)

#------------------attach image to the cell and change the image size-----
# ws = wb.worksheets[0]  # default the sheet1
img = openpyxl.drawing.image.Image('test2.png')
img.height = 238
img.width = 356
ws.add_image(img, 'B6')
img = openpyxl.drawing.image.Image('test1.png')
img.height = 238
img.width = 356
ws.add_image(img, 'I6')  # add image to the file at location L41
wb.save(file_name)

您有两次保存会导致IO错误
您不需要保存到最后,这样就可以删除第一次保存

import os
import openpyxl

print(os.getcwd())
file_name = 'a.xlsx'
wb = openpyxl.load_workbook(file_name)   # open exist excel file
ws = wb["Sheet1"]  # set the active sheet
sheet = wb.active
ws['a2'].value = 11112
# wb.save(file_name)     # <----- Save 1 can be removed

#------------------attach image to the cell and change the image size-----
# ws = wb.worksheets[0]  # default the sheet1
img = openpyxl.drawing.image.Image('test2.png')
img.height = 238
img.width = 356
ws.add_image(img, 'B6')
img = openpyxl.drawing.image.Image('test1.png')
img.height = 238
img.width = 356
ws.add_image(img, 'I6')  # add image to the file at location L41
wb.save(file_name) # <----- Save 2 is the only one needed

最新更新