将df保存在XLSM文件表中,而不会丢失图像和其他格式

时间:2020-02-13 10:22:53

标签: python-3.x pandas openpyxl

我有一个Main.xlsm文件和一个df。我想将df的完整值保存在Output文件的新表(称为Main.xlsm)中,而不会丢失.xlsm文件中的任何格式。

在Main.xlsm文件中,我有一张工作表,其中包含某些图像,某些合并的单元格等。

我的代码

output_file_name = "Main.xlsm"
output_intermin_path = r"C:\Users"
output_path = "%s\\%s" % (output_intermin_path,output_file_name)

book = load_workbook(output_path, keep_vba = True)
writer = pd.ExcelWriter(output_path, engine = 'openpyxl')
writer.book = book

df.to_excel(writer, sheet_name = 'Output')
writer.save()
writer.close()

上面的代码运行良好,但是问题是我松开了图像,必须合并某些单元格才能使它看起来精美。当我运行此代码时,我会松开所有这些东西!

1 个答案:

答案 0 :(得分:0)

您可以安装Pillow并导出所有图像。

pip install Pillow

然后从documentation

from openpyxl import Workbook
from openpyxl.drawing.image import Image

wb = Workbook()
ws = wb.active
ws['A1'] = 'You should see three logos below'

# create an image
img = Image('logo.png')

# add to worksheet and anchor next to cells
ws.add_image(img, 'A1')
wb.save('logo.xlsx')

源代码: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/drawing/image.html#Image