简体   繁体   中英

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. The aforementioned process should be done by using Python and ideally by using pywin32 (win32com.client).

The below code works great, but the Excel data can only be pasted at the beginning of the Word document:

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 :

# 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. Press Alt+F11 to open the VBA Editor, then F2 to start the Object Browser. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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