Graphs lost while overwriting to existing excel file in Python

丶灬走出姿态 提交于 2019-12-02 08:50:16

This is currently (version 2.2) not possible.

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  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!