我目前正在尝试使用 win32com python 库打开一个包含图表的 excel 文件,并将该图表保存为同一目录中的图像。
我试过下面的代码:
import win32com.client as win32
from win32com.client import Dispatch
import os
xlApp = win32.gencache.EnsureDispatch('Excel.Application')
# Open the workbook with the correct path
workbook = xlApp.Workbooks.Open("C:\\Users\\Owner\\PycharmProjects\\venv\\automaticexcelgrapherv4\\saveImageTest.xlsx")
xlApp.Sheets("Sheet1").Select()
xlApp.Visible = True
xlSheet1 = workbook.Sheets(1)
#Ensure to save any work before running script
xlApp.DisplayAlerts = False
i = 0
for chart in xlSheet1.ChartObjects():
chart.CopyPicture()
#Create new temporary sheet
xlApp.ActiveWorkbook.Sheets.Add(After=xlApp.ActiveWorkbook.Sheets(1)).Name="temp_sheet" + str(i)
temp_sheet = xlApp.ActiveSheet
#Add chart object to new sheet.
cht = xlApp.ActiveSheet.ChartObjects().Add(0,0,800, 600)
#Paste copied chart into new object
cht.Chart.Paste()
#Export image
#IMP: The next line exports the png image to the new sheet, however I would like to save it in the directory instead
cht.Chart.Export("chart" + str(i) + ".png")
i = i+1
xlApp.ActiveWorkbook.Close()
#Restore default behaviour
xlApp.DisplayAlerts = True
这会在 excel 文件中创建一个新工作表,并将图表的 .png 图像放入其中。但是,我不知道如何将该图像保存在目录中。