Using Python to implement the writing and saving methods of Word documents through Win32 COM

Source: Internet
Author: User
This article mainly introduces the use of Python through the Win32 COM implementation of Word document writing and preservation method, has a certain reference value, now share to everyone, the need for friends can refer to

The operation of the software through the Win32 COM interface is essentially consistent with the direct operating software, which is quite different from what I used to do with various extended components or libraries to implement various files. If you have experience with Word under Windows, then using Win32 COM should be a more convenient way.

Previously, the Word document was processed by piecing together the code on the network, and today a new attempt was made by reading the document from the beginning. Simple implementation of a Word file creation, writing and storage.

The implementation code is as follows:

#!/usr/bin/python Import osfrom win32com.client Import dispatchpwd = OS.GETCWD () WordApp = Dispatch (' Word. Application ') wordapp.visible = Truemydoc = WordApp.Documents.Add () MyRange = Mydoc.range (0,0) Myrange.insertbefore (' Hello python word doc! ') Mydoc.saveas (pwd + ' \\python_word_demo.docx ') mydoc.close () Wordapp.quit ()

The program runs without error reporting, and during the run, you see the opening of the word software and the process of closing the operation last. At the end of execution, there is one more file named Python_word_demo.docx in the current folder. Open the file to see what is written in it as follows:

In this way, the previously wanted to demonstrate functionality has been implemented, the implementation of the method is much simpler than I thought. This is certainly a good way to consider if there is a need for batch processing of files.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.