本文實例講述了python實現在windows下操作word的方法。分享給大家供大家參考。具體實現方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch( 'Word.Application' ) # 或者使用下面的方法,使用啟動獨立的進程: # w = win32com.client.DispatchEx('Word.Application') # 后臺運行,不顯示,不警告 w.Visible = 0 w.DisplayAlerts = 0 # 打開新的文件 doc = w.Documents. Open ( FileName = filenamein ) # worddoc = w.Documents.Add() # 創建新的文檔 # 插入文字 myRange = doc. Range ( 0 , 0 ) myRange.InsertBefore( 'Hello from Python!' ) # 使用樣式 wordSel = myRange.Select() wordSel.Style = constants.wdStyleHeading1 # 正文文字替換 w.Selection.Find.ClearFormatting() w.Selection.Find.Replacement.ClearFormatting() w.Selection.Find.Execute(OldStr, False , False , False , False , False , True , 1 , True ,NewStr, 2 ) # 頁眉文字替換 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 ) # 表格操作 doc.Tables[ 0 ].Rows[ 0 ].Cells[ 0 ]. Range .Text = '123123' worddoc.Tables[ 0 ].Rows.Add() # 增加一行 # 轉換為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 ) # 打印 doc.PrintOut() # 關閉 # doc.Close() w.Documents.Close(wc.wdDoNotSaveChanges) w.Quit() |
希望本文所述對大家的Python程序設計有所幫助。