简体   繁体   English

使用win32com时保存和关闭word文档

[英]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.我想确保我保存了 word 文档并在之后立即关闭它,以便我可以在 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?保存和关闭word文档的正确方法是什么? Thank you.谢谢你。

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:保存文档后,您应该关闭它,这与您对 Excel 工作簿所做的非常相似,因此您的代码应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM