[英]Paste Excel data in specific MS Word paragraph using win32com and Python
我想复制 Excel 数据(例如表格或特定范围)并将其粘贴到 MS Word 文档段落的末尾而不替换其文本。 上述过程应使用 Python 完成,最好使用 pywin32 (win32com.client)。
下面的代码效果很好,但是 Excel 数据只能粘贴在 Word 文档的开头:
def copy_from_excel_paste_to_word(word_filename, excel_filename):
# Word init
word = client.Dispatch("Word.Application")
word.Visible = True
report = word.Documents.Open(word_path)
wdRange = report.Content
# Excel init
excel = client.Dispatch("Excel.Application")
checklist = excel.Workbooks.Open(excel_path)
sheet = checklist.Worksheets("Names")
sheet.Range("B2:D15").Copy()
# Paste Excel data at the beginning of the doc, while keeping doc data
wdRange.Collapse(1)
wdRange.PasteExcelTable(False, False, False) # ? How can i specify the paste location ?
# Save and quit
word.ActiveDocument.Close(SaveChanges=True)
excel.Quit()
word.Quit()
折叠到末尾而不是任何Range
的开头:
# Paste Excel data at the end of the doc, while keeping doc data
wdRange.Collapse(0)
注意:要查看此类信息,请启动 Word。 按 Alt+F11 打开 VBA 编辑器,然后按 F2 启动 Object 浏览器。 例如,如果您在搜索框中键入“ Collapse
”,您可以单击它并按 F1 以获取帮助主题。
您还将在结果列表的下方看到条目WdCollapseDirection
,它将显示可以传递给Collapse
方法的值。 单击它,两个枚举将出现在底部列表中。 单击一个,然后在最底部的窗格中查看代码所需的数值(0 或 1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.