[Tutor] Using python to create and save a Ms Word file

Andrew Robert andrew.arobert at gmail.com
Fri Jul 21 14:55:48 CEST 2006


-----BEGIN PGP SIGNED MESSAGE-----

Hash: SHA1



Thanks for your help on this.

Here is the completed code in case anyone is interested.

#! C:\Python24\python 
#
# program: mswword.py
# Author:  Andrew Robert
# 
# Ver       Date       Programmer    Modification
# 1.0       07/20/06   AAR           Initial Creation
# 1.1       07/21/06   AAR           added doc save/quit items to class
# 1.2                                added argument and source/target file testing 

import sys, time, string, win32com.client, stat, os

class CWordAutomate:
    """Encapsulates a winword com connection"""
    def __init__( self ):
        """construct: create OLE connection to winword"""
        self.m_obWord         = win32com.client.Dispatch( "Word.Application" )
        self.m_obDoc          = self.m_obWord.Documents.Add( ) # create new doc
        self.m_obWord.Visible = 1
        self.m_Sel            = self.m_obWord.Selection # get a selection

    def WriteLine( self, sTxt, sFont, lSize, bBold=0 ):
        """Write a line to winword"""
        self.m_Sel.Font.Name = sFont
        self.m_Sel.Font.Bold = bBold
        self.m_Sel.Font.Size = lSize
        self.m_Sel.TypeText( Text=sTxt + "\n"  )

    def Save(self, sFilename):
        self.m_obDoc.SaveAs(sFilename)

    def Quit(self):
        self.m_obWord.Quit()


def file_test(file):
    """
    Tests user supplied file to see if it exists and contains data.
    If the input file does not exist or is empty, return a warning code
    """

    if (0 == os.path.isfile(file) or (0 == os.stat(file)[stat.ST_SIZE])):
        return 1
    else:
        return 0


if __name__ == "__main__":

	usage = "\n\n\tUsage:  msword.py  {inputfile}  {outputfile}\n"

	#
	# Test number of arguments passed.
	#
	if len(sys.argv) != 3:
		print "\n\n\tmsword.py error: \n\n\tInsufficient arguments passed."
		print usage
		sys.exit(1)

	
	# Test source file to ensure it exists and contains data
	if file_test(sys.argv[1]) == 1 : 
		print "\n\n\tmsword.py error: \n\n\tSource file not found or is empty."
		print usage
		sys.exit(1)

	# Test target file to prevent accidental clobbering
	if file_test(sys.argv[2]) == 0 :
		print "\n\n\tmsword.py error: \n\n\tTarget file already exists."
		print usage
		sys.exit(1)


	sFileName  = sys.argv[1]
	obFile     = file( sFileName, 'r+' )
	sContent   = obFile.read()
	obFile.close()
	lstContent = sContent.splitlines()
	
	# 
	# Write contents of source file to user supplied file name
	#
	obWord = CWordAutomate()
	
	for sLine in lstContent:
		obWord.WriteLine( sLine, "Courier New", 10  )
	
	sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
	obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )
	
	obWord.Save(sys.argv[2])
	obWord.Quit()



andrew clarke wrote:
> On Thu, Jul 20, 2006 at 01:25:26PM -0400, Andrew Robert wrote:
> 
>> I have a text file being broadcast on a web site and I would like to download it 
>> and save it as an MS Word file.
> 
> ...
> 
>> I found the following code on the web that comes close to what i need.
>>
>> It:
>>
>> - - reads a file passed to it
>> - - opens word file 
>> - - dumps the read contents to the file
>> - - places a time stamp at the end signaling when the conversion occured
>>
>> What is is missing is how to automate saving/closing the file when the conversion is complete.
>>
>> Would someone be able to help fill in the blanks on this?
> 
> I've never played with Win32 COM before, but your message inspired me to
> learn.  :-)
> 
> A quick Google later, and it seems you need to add the following methods
> to the CWordAutomate class:
> 
>     def Save(self, sFilename):
>         self.m_obDoc.SaveAs(sFilename)
> 
>     def Quit(self):
>         self.m_obWord.Quit()
> 
> Then in your code:
> 
>> sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
>> obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )
> 
> Add these:
> 
> obWord.Save("blah.doc")
> obWord.Quit()
> 
> On my system, "blah.doc" was saved as
> 
> C:\Documents and Settings\ozzmosis\My Documents\blah.doc
> 
> So you'll need to specify an absolute pathname if you want it to be
> saved somewhere else.
> 
> I picked this up from:
> 
> http://mail.python.org/pipermail/python-win32/2002-June/000396.html
> 
> I guess we both need to subscribe to the python-win32 mailing list...  ;-)
> 
> Regards
> Andrew
> 
-----BEGIN PGP SIGNATURE-----

Version: GnuPG v1.2.1 (MingW32)

Comment: GnuPT 2.7.2



iD8DBQFEwM7UDvn/4H0LjDwRAteBAKCQuk2mwsroT9Nw49j6iqS0a2b13ACfdQNP

L6GWNQORnZjWOvMBrjhHpr8=

=fS7m

-----END PGP SIGNATURE-----



More information about the Tutor mailing list