python操作office办公软件(excel)。本文对涉及xls文件读写上不方便。如果你需要通过python读写xls文件,可以参考http://blog.csdn.net/luanpeng825485697/article/details/78595320
前提条件是电脑已经安装了office办公软件,并且下载安装了pywin32-217.win32-py2.7库。
安装python库的方法,可以参考Python库的安装与卸载
然后就可以使用python编程操作excel软件了,excel软件的启动可能会比较慢,所以有可能要等待几秒才能启动成功。
python2.7下代码
#coding:utf-8#python控制excel软件,本机电脑需要安装office软件from Tkinter import Tkfrom time import sleepfrom tkMessageBox import showwarningimport win32com.client as win32warn = lambda app: showwarning(app, 'Exit?') #弹出提示框def excel(): app = 'Excel' xl = win32.gencache.EnsureDispatch('%s.Application' % app) #创建excel对象 ss = xl.Workbooks.Add() #添加一个工作簿 sh = ss.ActiveSheet #取得活动(当前)工作表 xl.Visible = True #设置为桌面显示可见 sleep(1) #暂停一下,让用户看清演示的每一步 sh.Cells(1,1).Value = 'first line' sleep(1) #暂停一下,让用户看清演示的每一步 for i in range(3, 8): sh.Cells(i,1).Value = 'line %d' % i #在3到8行,第一列,写入内容 sleep(1) #暂停一下,让用户看清演示的每一步 sh.Cells(i+2,1).Value = "last line" sh.Range(sh.Cells(1, 1), sh.Cells(4, 1)).Font.Bold = True #设置指定区域的字体格式 warn(app) #弹出警告消息 ss.Close(False) #工作簿关闭保存 xl.Application.Quit() #excel应用退出if __name__=='__main__': Tk().withdraw() #不让tk顶级窗口出现,因为默认tk会自动创建一个顶级窗口,而且不会将其隐藏 excel()python3.6下代码
#coding:utf-8#python控制excel软件,本机电脑需要安装office软件from tkinter import Tkfrom time import sleepfrom tkinter.messagebox import showwarningimport win32com.client as win32warn = lambda app: showwarning(app, 'Exit?') #弹出提示框def excel(): app = 'Excel' xl = win32.gencache.EnsureDispatch('%s.Application' % app) #创建excel对象 ss = xl.Workbooks.Add() #添加一个工作簿 sh = ss.ActiveSheet #取得活动(当前)工作表 xl.Visible = True #设置为桌面显示可见 sleep(1) #暂停一下,让用户看清演示的每一步 sh.Cells(1,1).Value = 'first line' sleep(1) #暂停一下,让用户看清演示的每一步 for i in range(3, 8): sh.Cells(i,1).Value = 'line %d' % i #在3到8行,第一列,写入内容 sleep(1) #暂停一下,让用户看清演示的每一步 sh.Cells(i+2,1).Value = "last line" sh.Range(sh.Cells(1, 1), sh.Cells(4, 1)).Font.Bold = True #设置指定区域的字体格式 warn(app) #弹出警告消息 ss.Close(False) #工作簿关闭保存 xl.Application.Quit() #excel应用退出if __name__=='__main__': Tk().withdraw() #不让tk顶级窗口出现,因为默认tk会自动创建一个顶级窗口,而且不会将其隐藏 excel()| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |