Graphs lost while overwriting to existing excel file in Python

3k Views Asked by At

I'm using openpyxl to write to an existing file and everything works fine. However after the data is saved on the file, graphs disappear.

I understand Openpyxl currently only supports chart creation within a worksheet only. Charts in existing workbooks will be lost.

Are there any alternate libraries in Python to achieve this. I just want to feed a few values, so all the graphs and calculation happen in excel.

Thank you.

2

There are 2 best solutions below

0
On BEST ANSWER

This is currently (version 2.2) not possible.

0
On

I got some alternative solution to execute excel macro from python, that might be the solution for the above problem.

Create a ExcelWorkbook.xlsm and write the excel macro(which is very easy, excel macro recoding might help you) of what ever task you want to do and execute the macro from python. Graph and shape object will be safe.

openpyxl can be used to write and read the ExcelWorkbook.xlsm

from openpyxl import Workbook, load_workbook
import os
import win32com.client

#The excel macro should be written and saved (Excelworkbook.xlsm) before using this code. 
#Use macro codeExcelworkbook.xlsm to edit ExcelWorkBookContainGraph.xlsx
##################### Openpyxl #####################
#Open the Excelworkbook.xlsm (Macro workbook)
wb = load_workbook(filename='Excelworkbook.xlsm', read_only=False, keep_vba=True)
ws = wb.worksheets[0] #Worksheet will be sheet1[0]

##### Do the required task (read, write, copy..etc) in excel using openpyxl #####

#save Excelworkbook.xlsm
wb.save('Excelworkbook.xlsm')

#################### Run the excel macro #####################
if os.path.exists("Excelworkbook.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(Filename=os.path.dirname(os.path.abspath(__file__))+"\Excelworkbook.xlsm")#, ReadOnly=1)
    xl.Application.Run("Excelworkbook.xlsm!Module1.Macro1")
    xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl  

############### Working with excel contains Graph ###############
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename=os.path.dirname(os.path.abspath(__file__))+"\ExcelWorkBookContainGraph.xlsx")#, ReadOnly=1)
try:
    xl.ActiveWorkbook.SaveAs("C:\ExcelExample\ExcelWorkBookContainGraph.xlsx")#Change the save path as per your requirment
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl
except:
    #If you get some error while saving kill the running excel task in background
    print 'Error in saving file'
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl