Reputation: 93
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.
Upvotes: 0
Views: 4514
Reputation: 724
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()
Upvotes: 2