Python - Extra Excel chart series with win32com

后端 未结 1 1642
野趣味
野趣味 2021-01-07 15:46

I\'m writing some code for an assignment, and I need to create a simple column chart in Excel. This afternoon I found win32com (amazing tool by the way), but I\'ve been suff

相关标签:
1条回答
  • 2021-01-07 16:18

    By observing the behavior of recording a macro in Excel which performs the same actions as we are replication in Python we can see that there does not appear to be a need to create a new series such as

    series = chart.SeriesCollection().NewSeries()
    

    I was able to simply reference an existing series

    series = chart.SeriesCollection(1)
    

    The following code seems to give me the desired behavior on my computer.

    import win32com.client
    xlApp = win32com.client.Dispatch('Excel.Application')
    
    xlBook = xlApp.Workbooks.Add()
    
    xlSheet = xlBook.Sheets(1)
    xlSheet.Name = "Algoritmos de Busqueda"
    xlSheet.Cells(1,1).Value="Secuencial"
    xlSheet.Cells(2,1).Value="Binaria"
    xlSheet.Cells(1,2).Value="32"
    xlSheet.Cells(2,2).Value="32"
    
    chart = xlApp.Charts.Add()
    chart.Name= "Grafico "+xlSheet.Name
    series = chart.SeriesCollection(1)
    series.XValues= xlSheet.Range("A1:A2")
    series.Values= xlSheet.Range("B1:B2")
    series.Name= "Algoritmos"
    chart.Axes()[0].HasMajorGridlines = True
    

    This has been simplified to the bare minimum. I tested this in Python 2.7 with Excel 2003.

    0 讨论(0)
提交回复
热议问题