Search code examples
pythonpywin32

win32com.client: Unwanted 'save changes' dialog box from Word


My task is simple, I want to open a word template, add some text and tables to the word doc, save it as PDF and exit out of word.

Because of the nature of the beast I don't want to save the document in word format, and for it all to work the PDF needs to be generated with no user interaction with word.

There may be better ways of solving this task, but they are the parameters by which I am constrained. The other constraint is that it needs to run with python 2.4...

My starting point was Mark Hammonds easyword.py sample script, and I have got it to do most of what I want, but, there are two issues that I just cannot seem to figure out, and are probably related.

When I run the test() function I get my output PDF and Word docs generated correctly, but

1) I don't seem to be able to 'close' the word session/document 2) I end up with an annoying dialog box asking me if I want to save changes.

The dialog box is a deal breaker.

In my Quit function Close() doesn't appear to be recognised, and none of the tools I've got are giving me any methods at all for 'self.wordapp', although the self.wordapp.Quit() does appear to work (doesn't cause a crash).

I've spent hours searching for an answer to this, both on the internet and looking at similar code for Excel (formatting is why I can't using Excel) to no avail. Does anyone have any ideas?

The relevant sections of my test code are below:

import win32com.client

MYDIR = 'somevalidpath'

class WordWrap:
    ''' Wrapper around Word documents to make them easy to build.
        Has variables for the Applications, Document and Selection; 
        most methods add things at the end of the document
    '''
    def __init__(self, templatefile=None):
        self.wordApp = win32com.client.gencache.EnsureDispatch('Word.Application')
        if templatefile == None:
            self.wordDoc = self.wordApp.Documents.Add()
        else:
            self.wordDoc = self.wordApp.Documents.Add(Template=templatefile)

        #set up the selection
        self.wordDoc.Range(0,0).Select()
        self.wordSel = self.wordApp.Selection

    def Quit(self):
        self.wordApp.Close(SaveChanges=1)
        self.wordApp.Quit()

def test():
    '''
    Test function for class 
    '''
    outfilename = MYDIR + '\\pythonics_mgt_accounts.doc'

    w = WordWrap(MYDIR + '\\pythonics.dot')
    #w.show()
    w.addStyledPara('Accounts for April', 'Title')

    #first some text
    w.addStyledPara("Chairman's Introduction", 'Heading 1')
    w.addStyledPara(randomText(), 'Normal')

    # now a table sections
    w.addStyledPara("Sales Figures for Year To Date", 'Heading 1')
    data = randomData()
    w.addTable(data, 37) # style wdTableStyleProfessional
    w.addText('\n\n')

    # finally a chart, on the first page of a ready-made spreadsheet
    w.addStyledPara("Cash Flow Projections", 'Heading 1')
    w.addInlineExcelChart(MYDIR + '\\wordchart.xls', 'Cash Flow Forecast')

    w.saveAs(outfilename)
    print 'saved in', outfilename

    # save as PDF, saveAs handles the file conversion, based on the file extension
    # the file is not just being renamed and saved
    new_name = outfilename.replace(".doc", r".pdf")
    w.saveAs(new_name)
    print 'saved in', new_name

    w.Quit()

Solution

  • Doh, it would have helped if I'd tried to close the document, and not the application. Code should read self.wordDoc.Close()