Office files are our daily work lives are frequently used file format
type, in which the Word file format most commonly used.
Python by Win32com New member of Micro so-bit Office file
access, Python and the inner member has straight Win32com New York, you do not need
to install. Use Win32com New Zealand handling Microsoft Office files,
your computer must have been installed Microso Enterprise Office.
Implement the new file and save
the following components we import Win32com
client module:
Word processing application Word file must first build. The syntax is:
New File
Win32com the new file component is achieved by Documents Add method syntax is:
For example, the variable name of the new file to doc:
Location of the file contents can be set by the Range method file variable, the syntax is:
Start and end positions is an integer representing the number of characters. For example, the first 10 files saved characters
to rangel variables:
Inserting text into Word document may be implemented in two ways. One method is InsertA Pat mound r, this side
method to insert text into a variable range of the end position, after the insertion position of the variable value to change the end position,
the syntax is:
Another method is the InsertBefore, this text is inserted into the starting position in front of the variable range,
the syntax is:
Use ln sertBefore method does not change the position of the start value of the variables inserted text, used again
when InsertBefore method, or will be inserted into the text variable values before the initial starting position.
Save the file
because they do not access the file when Win32com component
can use a relative path, it must first obtain the path where Python program file, the syntax is:
Save the Word file syntax is:
For example, the file is saved in the media folder, the file name testl.docx:
Word processed documents, usually the last to close in the program Word files and applications, to avoid consuming system resources
source, the syntax is:
Establish Word file Win32com assembly, after insertion of saving.
Import OS from the win32com Import Client Word = client.gencache.EnsureDispatch ( ' the Word.Application ' ) word.Visible =. 1 word.DisplayAlerts = 0 DOC = word.Documents.Add () Range1 = doc.Range (0,0) # start of the file range1.InsertAfter ( " this is a test of the first row \ n this is the second test line \ n " ) range1.InsertAfter ( " this is a test of the third row \ n this is a test of the fourth row \ n " ) range1.InsertBefore ( " the first time the file is inserted into the forefront of \ the n- " ) range1.InsertBefore (" Inserted again into the forefront of the file \ the n- " ) # the cpath = os.path.dirname (__ file__) doc.SaveAs ( " E: \\ Media \\ test1.docx " ) doc.close () word.Quit ()