2015-06-24 67 views
0

我使用openpyxl寫入現有文件,並且一切正常。但是,數據保存在文件後,圖形消失。在覆蓋Python中現有的Excel文件時丟失圖形

我知道Openpyxl目前只支持在工作表中創建圖表。現有工作簿中的圖表將會丟失。

在Python中是否有任何替代庫來實現這一點。我只是想提供一些值,所以所有的圖表和計算都在Excel中進行。

謝謝。

回答

0

這是目前(版本2.2)不可能的。

0

我得到了一些替代解決方案來執行從Python的Excel宏,這可能是解決上述問題。

創建一個ExcelWorkbook.xlsm,然後編寫您想要執行的任務並從python執行宏的excel宏(這很容易,excel宏重新編碼可能會幫助您)。圖形和形狀對象將是安全的。

openpyxl可用於寫入和讀取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