1
votes

I want to copy Excel data (e.g. 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()
1
You can control the location of the table by specifying in what Range-Object to add it. Currently, you collapse the entire document into a range and paste it in front of that range: docs.microsoft.com/en-us/office/vba/api/word.range.collapse - tst
@tst Thanks for your answer. It would be great if you could provide me a code example. - dropdown
I dont have the means to test it right now, but try iterating over the StoryRanges for rng in report.StoryRanges and then scan the rng for specific identifiers - tst
@tst Thank you anyway! How am i supposed to know all these methods (e.g. StoryRanges) and their properties since there is not relevant (detailed) documentation? - dropdown
Read the Word Object Model. Check what objects are contained in a "Document" (equvalent to your "report") and what each of the child-objects are. A "Range" in VBA can be anything between a single character, a whole sentence in a paragraph, a full paragraph or the whole document. Play around with that and you should find a way that works for you. docs.microsoft.com/en-us/visualstudio/vsto/… - tst

1 Answers

0
votes

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