2013年10月19日土曜日

simple Excel bar plot example using python's win32com module

Here is a simple example of Python interface with Excel using win32com module.
You can put other charts by setting the arguments in AddChart().
See the website below for the name of charts.


import win32com.client
from win32com.client import constants as c
import numpy as np


def main():
    xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
    xl.Visible = True
    wb = xl.Workbooks.Add()
    #wb = xl.Workbooks.Open(r"C:\Users\test.xls")
    ws = xl.ActiveSheet

    x = np.arange(15)
    y = 0.1*x**2
    z = -y
    
    row = range(1,1+len(x))
    col = 1
    for xi, yi, zi, r in zip(x, y, z, row):
        ws.Cells(r,col).Value =  int(xi)
        ws.Cells(r,col+1).Value = float(yi)
        ws.Cells(r,col+2).Value = float(zi)

    chart = ws.Shapes.AddChart(c.xlColumnClustered).Select()
    xl.ActiveChart.SetSourceData(Source=ws.Range(ws.Cells(row[0], col+1), ws.Cells(row[-1], col+2)))
    xl.ActiveChart.SeriesCollection(1).XValues = ws.Range(ws.Cells(row[0], col), ws.Cells(row[-1], col))

if __name__ == "__main__":
    main()


0 件のコメント:

コメントを投稿