1. 程式人生 > >python應用系列教程——python操作office辦公軟體(excel)

python應用系列教程——python操作office辦公軟體(excel)

全棧工程師開發手冊 (作者:欒鵬)

然後就可以使用python程式設計操作excel軟體了,excel軟體的啟動可能會比較慢,所以有可能要等待幾秒才能啟動成功。

python2.7下程式碼

#coding:utf-8
#python控制excel軟體,本機電腦需要安裝office軟體
from Tkinter import Tk
from time import sleep
from tkMessageBox import showwarning
import win32com.client as win32

warn = 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 Tk
from time import sleep
from tkinter.messagebox import showwarning
import win32com.client as win32

warn = 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()