简体   繁体   English

使用 win32com 和 Python 将 Excel 数据粘贴到特定的 MS Word 段落中

[英]Paste Excel data in specific MS Word paragraph using win32com and Python

I want to copy Excel data (eg tables or specific range) and paste it at the end of a MS Word document's paragraph without replacing its text.我想复制 Excel 数据(例如表格或特定范围)并将其粘贴到 MS Word 文档段落的末尾而不替换其文本。 The aforementioned process should be done by using Python and ideally by using pywin32 (win32com.client).上述过程应使用 Python 完成,最好使用 pywin32 (win32com.client)。

The below code works great, but the Excel data can only be pasted at the beginning of the Word document:下面的代码效果很好,但是 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()

To collapse to the end instead of the beginning of any Range :折叠到末尾而不是任何Range的开头:

# Paste Excel data at the end of the doc, while keeping doc data
wdRange.Collapse(0)

Note: to see this kind of information, start Word.注意:要查看此类信息,请启动 Word。 Press Alt+F11 to open the VBA Editor, then F2 to start the Object Browser.按 Alt+F11 打开 VBA 编辑器,然后按 F2 启动 Object 浏览器。 If you then type, for example, Collapse into the search box you can then click on it and press F1 to get the Help topic.例如,如果您在搜索框中键入“ Collapse ”,您可以单击它并按 F1 以获取帮助主题。

You'll also see, further down in the results list, and entry WdCollapseDirection , which will show the values that can be passed to the Collapse method.您还将在结果列表的下方看到条目WdCollapseDirection ,它将显示可以传递给Collapse方法的值。 Click on that and two enumerations will appear in the bottom list.单击它,两个枚举将出现在底部列表中。 Click on one, then look in the pane at the very bottom to see the numerical value you need for your code (0 or 1).单击一个,然后在最底部的窗格中查看代码所需的数值(0 或 1)。

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

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