目錄:
1.1 安裝win32com模組
1.2 Access資料庫操作
1.2.1 建立db1.db資料庫,設計一張表t_student_b
1.3 Excel檔案操作
1.3.1 讀取Excel
1.4 Word檔案操作
1.4.1 示例1:開啟,另存為
1.4.2 示例2:更多功能
1.1 安裝win32com模組
下載地址:
http://sourceforge.net/projects/pywin32/
1.2 Access資料庫操作
1.2.1 建立db1.db資料庫,設計一張表t_student_b
示例
#Python操作Access資料庫步驟之1、建立資料庫連線
import win32com.client
conn = win32com.client.Dispatch(r'ADODB.Connection')
print '111'
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=d:\\python279\\db1.mdb;'
conn.Open(DSN)
print '222'
#Python操作Access資料庫步驟之2、開啟一個記錄集
rs = win32com.client.Dispatch(r'ADODB.Recordset')
rs_name = 't_student_b'#表名
rs.Open('[' + rs_name + ']', conn, 1, 3)
#Python操作Access資料庫步驟之3、對記錄集操作
rs.AddNew()
rs.Fields.Item(1).Value = '102'
rs.Fields.Item(2).Value = 'Li Yong'
rs.Update()
sql_statement = "insert into t_student_b (studno, studname) values ('201101', 'LiLee')"
#sql_statement = 'select * from t_student_b order by studno';
print '333'
conn.Execute(sql_statement)
print '444'
conn.Close()
1.3 Excel檔案操作
1.3.1 讀取Excel
編寫操作類
from win32com.client import constants, Dispatch
class EasyExcel:
def __init__(self, filename=None):
self.xlApp = Dispatch('Excel.Application')
if filename:
self.filename = filename
self.xlBook = self.xlApp.Workbooks.Open(filename)
else:
print "please input the filename"
def close(self):
self.xlBook.Close(SaveChanges=0)
del self.xlApp
def getCell(self, sheet, row, col):
"Get value of one cell"
sht = self.xlBook.Worksheets(sheet)
return sht.Cells(row, col).Value
def getRange(self, sheet, row1, col1, row2, col2):
"return a 2d array (i.e. tuple of tuples)"
sht = self.xlApp.Worksheets(sheet)
return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value
示例:
#from easyExcel import EasyExcel
#from texcel import EasyExcel
excelProxy = EasyExcel("d:\\python279\\test.xls")
content=excelProxy.getRange("sheet1",1,1,2,2)
print content
1.4 Word檔案操作
要使用Python控制MS Word,您需要先安裝win32com套件,這個套件可以到 http://sourceforge.net/projects/pywin32/ 找到。您需要先import win32com模組才能進行Word的控制。
1.4.1 示例1:開啟,另存為
from win32com.client import Dispatch, constants
from win32com.client.gencache import EnsureDispatch
EnsureDispatch('Word.Application') #makepy 匯入Word類庫,否則constants無法使用
msword = Dispatch('Word.Application')
msword.Visible = True #是否可見
msword.DisplayAlerts = 0
strDir='d:\\python279\\';
doc = msword.Documents.Open(FileName = strDir + r'test.doc') #開啟已有檔案
newdoc = msword.Documents.Add() #新增新檔案
newdoc.SaveAs('new.doc') #另存為
1.4.2 示例2:更多功能
#Python 操作Word(Excel、PPT等通用)
import win32com
from win32com.client import Dispatch, constants
w = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用啟動獨立的程式:
# w = win32com.client.DispatchEx('Word.Application')
# 後臺執行,不顯示,不警告
w.Visible = 1
w.DisplayAlerts = 0
filenamein = 'test.doc'
# 開啟新的檔案
#doc = w.Documents.Open( FileName = filenamein )
worddoc = w.Documents.Add() # 建立新的文件
# 插入文字
#myRange = doc.Range(0,0)
myRange = worddoc.Range(0,0)
myRange.InsertAfter('Hello from Python! 111\n')
w.Selection.TypeParagraph; #換行
myRange.InsertAfter('Hello from Python! 222\n')
#wordSel = myRange.Select()
myRange = worddoc.Range(0,0)
w.Selection.Style = constants.wdStyleHeading1 #找不到Style
# 正文文字替換
OldStr = 'Hello'
NewStr = 'How are you'
#w.Selection.Find.ClearFormatting()
#w.Selection.Find.Replacement.ClearFormatting()
#w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)
# 頁首文字替換
print('page header:')
#w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
#w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
#w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2)
# 表格操作
print('table:')
#myRange = worddoc.Range(0,0)
#worddoc.Tables.Add(myRange, 5, 4)
w.Selection.TypeParagraph; #換行
#w.Selection.TypeText = 'test';
#w.Content.InsertAfter.Text = 'test'
#w.Selection.TypeParagraph;
myRange = worddoc.Range(worddoc.Sentences.Last.End -1,worddoc.Sentences.Last.End -1)
#w.Selection.Style = '正文'
w.Selection.ClearFormatting()
myRange.InsertAfter('Hello from Python! 333\n')
myRange.InsertAfter('Hello from Python! 444\n')
myRange.InsertAfter('Hello from Python! 555\n')
myRange.InsertAfter('Hello from Python! 333\n')
myRange = worddoc.Range(worddoc.Sentences.Last.End -1,worddoc.Sentences.Last.End -1)
w.ActiveDocument.Tables.Add(myRange, 2, 5)
#w.ActiveDocument.Tables.Add(wmyRange, 2, 5)
'''
if w.Selection.Tables(1).Style <> "網格型":
w.Selection.Tables(1).Style = "網格型"
w.Selection.Tables(1).ApplyStyleHeadingRows = True
w.Selection.Tables(1).ApplyStyleLastRow = True
w.Selection.Tables(1).ApplyStyleFirstColumn = True
w.Selection.Tables(1).ApplyStyleLastColumn = True
'''
#w.Selection.
#worddoc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
#worddoc.Tables[0].Rows.Add() # 增加一行
# 轉換為html
print('html:')
filenameout = 'd:\\python279\\mytest.html';
wc = win32com.client.constants
w.ActiveDocument.WebOptions.RelyOnCSS = 1
w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
w.ActiveDocument.WebOptions.OrganizeInFolder = 0
w.ActiveDocument.WebOptions.UseLongFileNames = 1
w.ActiveDocument.WebOptions.RelyOnVML = 0
w.ActiveDocument.WebOptions.AllowPNG = 1
#w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML ) # right work
# 列印
#doc.PrintOut()
#worddoc.PrintOut()
# 關閉
#doc.Close()
#worddoc.Close()
#w.Documents.Close(wc.wdDoNotSaveChanges)
#w.Quit()
其他例子: