通过Python添加chartobject到excel

所以我一直试图添加一个图表对象到使用IronPython的Excel文件,每当我调用ws.ChartObjects时我总是收到一个错误。 由于某种原因,它告诉我它是一个DispCallable,它没有Add属性。

clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') from Microsoft.Office.Interop import Excel System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo("en-US") from System.Runtime.InteropServices import Marshal def SetUp(xlApp): # supress updates and warning pop ups xlApp.Visible = False xlApp.DisplayAlerts = False xlApp.ScreenUpdating = False return xlApp def ExitExcel(filePath, xlApp, wb, ws): # clean up before exiting excel, if any COM object remains # unreleased then excel crashes on open following time def CleanUp(_list): if isinstance(_list, list): for i in _list: Marshal.ReleaseComObject(i) else: Marshal.ReleaseComObject(_list) return None wb.SaveAs(str(filePath)) xlApp.ActiveWorkbook.Close(False) xlApp.ScreenUpdating = True CleanUp([ws,wb,xlApp]) return None def GetWidthHeight(origin, extent, ws): left = ws.Cells(bb.xlRange(cellRange)[1], bb.xlRange(cellRange)[0]).Left top = ws.Cells(bb.xlRange(cellRange)[1], bb.xlRange(cellRange)[0]).Top width = ws.Range[origin, extent].Width height = ws.Range[origin, extent].Height return [left, top, width, height] if runMe: message = None try: xlApp = SetUp(Excel.ApplicationClass()) errorReport = None xlApp.Workbooks.open(str(filePath)) wb = xlApp.ActiveWorkbook ws = xlApp.Sheets(sheetName) # i have no clue why ws.ChartObjects.Count throws an error all the time origin = ws.Cells(bb.xlRange(cellRange)[1], bb.xlRange(cellRange)[0]) extent = ws.Cells(bb.xlRange(cellRange)[3], bb.xlRange(cellRange)[2]) left = GetWidthHeight(origin, extent, ws)[0] top = GetWidthHeight(origin, extent, ws)[1] width = GetWidthHeight(origin, extent, ws)[2] height = GetWidthHeight(origin, extent, ws)[3] xlChartObject = ws.ChartObjects.Add(int(left), int(top), int(width), int(height)) Marshal.ReleaseComObject(extent) Marshal.ReleaseComObject(origin) ExitExcel(filePath, xlApp, wb, ws) except: # if error accurs anywhere in the process catch it import traceback errorReport = traceback.format_exc() 

我的问题是调用ws.ChartObjects.Add()抛出一个exception“DispCallable”对象没有属性“添加”。 我该如何解决这个问题? 哪里不对?

基于类似的问题,指出ChartObjects是一个你应该使用的函数

 ChartObjects().Add(...) 

根据官方文件 ,论据应该是double 。 如果这不是问题,你可以分裂

 xlChartObject = ws.ChartObjects.Add(... 

 xlChartObjects = ws.ChartObjects xlChartObject = xlChartObjects.Add(... 

开始debugging。 这是一个好主意:

  1. 检查可用的方法(例如xlChartObjects类) 如何获取Python类中的方法列表? 或者查找一个对象有什么方法 。
  2. 检查types与什么是规范的方式来检查types的Python? 。

你可能会学习如何解决这些问题。

PS:在你发布的sheetNamebb的代码中没有定义,虽然你可能早些时候定义它们。