一个简单的用win32com调用Excel做函数图像的例子,本程序使用剪贴板向Excel传输数据。 调用参数:functions min max points * functions是一个用逗号隔开的函数列表,自变量名是x,中间不能有空格。 * min是x轴的最小值 * max是x轴的最大值 * points是描绘图像的点数 例如:draw.py sin(x)/x,sin(x)/x*0.5*(1-cos(2*3.1415926*(x+20)/40)) -20 20 1000 {{attachment:excelfunc.GIF}} {{{ #!python # com client for excel from math import * from win32com.client import Dispatch from win32com.client import constants from sys import * from string import * import win32clipboard as w def evalFunc(func, x): try: return eval(func) except: return "" funcs, xmin, xmax, points = argv[1], float(argv[2]), float(argv[3]), int(argv[4]) funclist = funcs.split(",") xdata = [float(x)/points * (xmax - xmin) + xmin for x in range(0,points)] ydata = [ [evalFunc(func, x) for x in xdata] for func in funclist] xlApp = Dispatch("Excel.Application") xlApp.Visible = True xlApp.Workbooks.Add() sheet = xlApp.ActiveWorkbook.ActiveSheet for n, f in enumerate(["x"] + funclist): sheet.Cells(1,n+1).Value = f def setClipText(aString): w.OpenClipboard() w.EmptyClipboard() w.SetClipboardText(aString) w.CloseClipboard() def setExcelText(sheet, x, y, clipstr): sheet.Cells(x,y).Select() setClipText(clipstr) sheet.Paste() for n, data in enumerate([xdata] + ydata): setExcelText(sheet, 2, n+1, "\n".join(map(str, data))) xlApp.Charts.Add() chart = xlApp.ActiveChart chart.ChartType = constants.xlXYScatterSmoothNoMarkers range = "A1:%s%d" % (ascii_uppercase[len(funclist)],points+1) chart.SetSourceData (Source=sheet.Range(range), PlotBy=constants.xlColumns) chart.Location(constants.xlLocationAsObject, sheet.Name) #xlApp.Visible = True }}} = 反馈 = * 如果是函数图表制作, gunplot 等等优秀软件比使用 Excel 要方便和快捷的多哪………… ZoomQuiet