win32com.客户端:Word中不需要的“保存更改”对话框

2024-06-10 22:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务很简单,我想打开一个word模板,在word文档中添加一些文本和表格,将其保存为PDF并退出word。在

由于beast的特性,我不想将文档保存为word格式,要使其正常工作,需要在不与word进行用户交互的情况下生成PDF。在

也许有更好的方法来解决这项任务,但它们是限制我的参数。另一个限制是它需要与Python2.4一起运行。。。在

我的出发点是马克·哈蒙德easyword.py示例脚本,我已经让它做了我想做的大部分事情,但是,有两个问题我似乎无法解决,而且可能是相关的。在

当我运行test()函数时,我可以正确地生成输出的PDF和Word文档,但是

1)我似乎无法“关闭”word会话/文档 2) 最后,一个恼人的对话框问我是否要保存更改。在

该对话框是一个交易破坏者。在

在我的Quit函数中Close()似乎没有被识别,而且我所拥有的工具也没有一个为'self.wordapp'虽然self.wordapp.退出()似乎可以工作(不会导致崩溃)。在

我花了好几个小时来寻找答案,无论是在互联网上还是在寻找类似的Excel代码(格式化是我不能使用Excel的原因)都没有结果。有人有什么想法吗?在

我的测试代码的相关部分如下:

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()

Tags: the文档selfforpdfdefquitword