在Python中覆盖现有excel文件时图形丢失

时间:2015-06-24 07:50:00

标签: python excel openpyxl

我使用openpyxl写入现有文件,一切正常。但是,在将数据保存到文件后,图形将消失。

据我所知,Openpyxl目前仅支持在工作表中创建图表。现有工作簿中的图表将丢失。

Python中是否有任何备用库来实现此目的。我只想提供一些值,所以所有图表和计算都在excel中进行。

谢谢。

2 个答案:

答案 0 :(得分:0)

目前(版本2.2)不可能。

答案 1 :(得分:0)

我从python中获得了一些替代解决方案来执行excel宏,这可能是解决上述问题的方法。

创建一个ExcelWorkbook.xlsm并编写excel宏(非常简单,excel宏重新编码可能会帮助你)你想做什么任务并从python执行宏。图形和形状对象将是安全的。

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