0

Problem

Referring to the code below, whenever I run this piece of code, it will find the charts all the sheets and exporting as an image. However, when it comes to chartObject.Chart.Export("chart" + str(i) + ".png") , it always exports to document folder in window.

Question

Is there a way to declare a path for it to be exported? (P.s) I have tried reading the documentation but there is no information regarding to my question. Thanks.

Code

1 thing to note: this piece of code was answered in 1 of the stackoverflow question way back in 2018. Hence, I do not own the credit for it. But I am working on something similar. Thanks.

from win32com.client import Dispatch

app = Dispatch("Excel.Application")
workbook_file_name = 'Programmes.xlsx'
workbook = app.Workbooks.Open(Filename=workbook_file_name)

# WARNING: The following line will cause the script to discard any unsaved changes in your workbook
app.DisplayAlerts = False

i = 1
for sheet in workbook.Worksheets:
    for chartObject in sheet.ChartObjects():
        # print(sheet.Name + ':' + chartObject.Name)
        chartObject.Chart.Export("chart" + str(i) + ".png")
        i += 1

workbook.Close(SaveChanges=False, Filename=workbook_file_name)
Shreamy
  • 341
  • 2
  • 16

1 Answers1

1

Solution

Hey guys, sorry for me posting my answer. But after some trial and error, I have figure out the solution

chartObject.Chart.Export("chart" + str(i) + ".png")

Simply add the path along with the file name. Example:

chartObject.Chart.Export(os.getcwd() + "/chart" + str(i) + ".png")

For those who are not sure what is os.getcwd() it basically means the current directory where the file of your code is.

Note: Never use os.path.join() cause you will get an error hence is safe to use as stated above.

Shreamy
  • 341
  • 2
  • 16