3

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)
2
  • "If you want to add text to the document, then you’ll want to tell Word where you want the text to go. That’s where the Range method comes in. While you can’t see it, there is a “grid” of sorts that tells Word how to layout the text onscreen. So if we want to insert text at the very top of the document, we tell it to start at (0,0)" - snippet from this article blog.pythonlibrary.org/2010/07/16/… Commented May 24, 2018 at 8:42
  • stackoverflow.com/questions/13509207/… check this out as well Commented May 24, 2018 at 8:43

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.