I am currently trying to use the win32com python library to open an excel file which contains a chart, and save that chart as an image in the same directory.
I have tried the code below:
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
This creates a new sheet inside the excel file and puts the .png image of the chart inside it. However, I do not know how to then save that image in the directory.