Seemab Hassan
Seemab Hassan

Reputation: 51

How to paste excel table into word using python

I am trying to copy an excel table into a word file with it's formatting intact and so far have found below mentioned code. but this code, while pasting into word, removes all the other content from the Word File. Please help, how to just append into existing word document instead of overwriting it?

from win32com import client
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open("C:/word_file.docx")
book = excel.Workbooks.Open("C:/excel_file.xlsx")
sheet = book.Worksheets(1)
sheet.Range("A1:D20").Copy()      # Selected the table I need to copy
doc.Content.PasteExcelTable(False, False, False)

Upvotes: 3

Views: 12230

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

I don't really know Python, but extrapolating from the code snippet you show us, see how to assign the entire body of the document to a Word.Range (as opposed to Excel.Range) object. Then you need to collapse the Range, either to its starting or its end point - think of it like pressing the left or right arrow key to "collapse" a selection to a point. Then you can insert new content without disturbing the existing content.

from win32com import client
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open("C:/word_file.docx")
book = excel.Workbooks.Open("C:/excel_file.xlsx")
sheet = book.Worksheets(1)
sheet.Range("A1:D20").Copy()      # Selected the table I need to copy
wdRange = doc.Content
wdRange.Collapse(1) #start of the document, use 0 for end of the document
wdRange.PasteExcelTable(False, False, False)

Upvotes: 2

Related Questions