This article mainly introduces how to use python to operate on word in windows. it involves some skills related to how to use Python to perform operations such as opening, inserting, converting, and printing. it is of great practical value, for more information about how to use python to operate word in windows, see the following example. Share it with you for your reference. The specific implementation method is as follows:
Import win32comfrom win32com. client import Dispatch, constantsw = win32com. client. dispatch ('Word. application ') # or use the following method to start an independent process: # w = win32com. client. dispatchEx ('Word. application ') # run in the background, not displayed, no warning w. visible = 0w. displayAlerts = 0 # open a new file doc = w. documents. open (FileName = filenamein) # worddoc = w. documents. add () # Create a new document # insert the text myRange = doc. range (0, 0) myRange. insertBefore ('Hello from Python! ') # Use the style wordSel = myRange. select () wordSel. style = constants. wdStyleHeading1 # text replacement w. selection. find. clearFormatting () w. selection. find. replacement. clearFormatting () w. selection. find. execute (OldStr, False, True, 1, True, NewStr, 2) # replace w with the header text. 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, True, 1, False, NewStr, 2) # table operation doc. tables [0]. rows [0]. cells [0]. range. text = '000000' worddoc. tables [0]. rows. add () # Add a row # Convert to 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) # print doc. printOut () # Close # doc. close () w. documents. close (wc. wdDoNotSaveChanges) w. quit ()
I hope this article will help you with Python programming.