Search code examples
pythonms-wordsyntax-errorwin32com

Save and close word document when using win32com


I want to make sure I save the word document and close it right after so I can further edit it in the next command in python.

from win32com import client
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open(r"C:\Users\crist\word_automation\Summary_template\Summary_output.docx")
book = excel.Workbooks.Open(r"C:\Users\crist\word_automation\Summary_template\summary3.xlsx")
sheet = book.Worksheets(1)
sheet.Range("A1:G5").Copy()    
wdRange = doc.Content
wdRange.Collapse(0)
wdRange.PasteExcelTable(False, False, False) 
book.SaveAs(r"C:\Users\crist\word_automation\Summary_template\summary3.xlsx")
book.Close()
excel.Quit()

doc.SaveAs(r"C:\Users\crist\word_automation\Summary_template\Summary_output.docx")

I don't think this last line is correct. What's the right way of saving and closing the word document? Thank you.


Solution

  • After you save the document you should close it, pretty similar to what you have done with the Excel Workbook, so your code should be:

    from win32com import client
    excel = client.Dispatch("Excel.Application")
    word = client.Dispatch("Word.Application")
    doc = word.Documents.Open(r"C:\Users\crist\word_automation\Summary_template\Summary_output.docx")
    book = excel.Workbooks.Open(r"C:\Users\crist\word_automation\Summary_template\summary3.xlsx")
    sheet = book.Worksheets(1)
    sheet.Range("A1:G5").Copy()    
    wdRange = doc.Content
    wdRange.Collapse(0)
    wdRange.PasteExcelTable(False, False, False) 
    book.SaveAs(r"C:\Users\crist\word_automation\Summary_template\summary3.xlsx")
    book.Close()
    excel.Quit()
    doc.SaveAs(r"C:\Users\crist\word_automation\Summary_template\Summary_output.docx")
    doc.Close()
    word.Quit()