本文實(shí)例講述了python實(shí)現(xiàn)在windows下操作word的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
import win32comfrom win32com.client import Dispatch, constantsw = win32com.client.Dispatch('Word.Application')# 或者使用下面的方法,使用啟動獨(dú)立的進(jìn)程:# w = win32com.client.DispatchEx('Word.Application')# 后臺運(yùn)行,不顯示,不警告w.Visible = 0w.DisplayAlerts = 0# 打開新的文件doc = w.Documents.Open( FileName = filenamein )# worddoc = w.Documents.Add() # 創(chuàng)建新的文檔# 插入文字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() # 增加一行# 轉(zhuǎn)換為htmlwc = win32com.client.constantsw.ActiveDocument.WebOptions.RelyOnCSS = 1w.ActiveDocument.WebOptions.OptimizeForBrowser = 1w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4w.ActiveDocument.WebOptions.OrganizeInFolder = 0w.ActiveDocument.WebOptions.UseLongFileNames = 1w.ActiveDocument.WebOptions.RelyOnVML = 0w.ActiveDocument.WebOptions.AllowPNG = 1w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML )# 打印doc.PrintOut()# 關(guān)閉# doc.Close()w.Documents.Close(wc.wdDoNotSaveChanges)w.Quit()
希望本文所述對大家的Python程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選