3.中级实例
上一篇博客,主要用于让你使用Python控制Microsoft Office产品进行入门。接下来的实例,将真正运用于现实世界中。
应用:从网上下载股票数据,然后直接插入Excel中。
摘自:python核心编程(第三版)
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import Tk
from time import sleep,ctime
from tkinter.messagebox import showwarning
import requests
import win32com.client as win32
import re
warn=lambda app:showwarning(app,'Exit?')
RANGE=range(3,8)
COLS=('TICKER','PRICE','CHG','%AGE')
URL='http://hq.sinajs.cn/list=s_sh000001'
def excel():
app = 'Excel'
'''
静态调动,PythonWin运行Makepy工具,创建应用所需的对象
动态调动代码:x1=win32.Dispatch('{0}.Application'.format(app))
'''
x1 = win32.gencache.EnsureDispatch('{0}.Application'.format(app))
# 新建一个sheet
ss = x1.Workbooks.Add()
# 激活sheet
sh = ss.ActiveSheet
# 设置桌面上可见
x1.Visible = True
sleep(1)
#设置单元格数值
sh.Cells(1,1).Value='Python-to-{0} Stock Quote Demo'.format(app)
sleep(1)
sh.Cells(3,1).Value='Prices quoted as of: {0}'.format(ctime())
sleep(1)
sh.Cells(5, 1).Value ='上证指数'
sleep(1)
for i in range(