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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Seemab Hassan
  • 51
  • 1
  • 1
  • 5
  • "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 http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/ – letroot May 24 '18 at 08:42
  • https://stackoverflow.com/questions/13509207/ms-word-r-w-in-python-python-docx-issue-and-win32com-references check this out as well – letroot May 24 '18 at 08:43

1 Answers1

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)
Cindy Meister
  • 25,071
  • 21
  • 34
  • 43