Jules Veltz
Jules Veltz

Reputation: 1

How can I automaticallly copy data from excel and paste into a word?

I tried to used docxtpl with Python, but the return is very ugly, neerly unreadable. I tried using Dataframe, list, ... but I doesn't have a clean table in my word. Does any one know how to make it with Python ? Or is it more simple using VBA ?

(And docx doesn't allow me to add INSIDE the Word, the table i want.) With Dataframe the table is trounce. And with list, the columns doesn't fit....

Thanks a lot

from docxtpl import DocxTemplate
doc = DocxTemplate(fichier_test)
context = {para_multiple[i]: liste_dataframe[i] for i in range(len(para_multiple))}
doc.render(context)
doc.save(file_location)

Where para_multiple is a list with all the tags in the .doc and liste_dataframe, the list of dataframe containing the data i need on the doc.

(This is what I get for now, i can't find out how to display it correctly) I need to delete the tabulation and the index

https://i.sstatic.net/r3CQJ.png

Upvotes: 0

Views: 1336

Answers (1)

PAP
PAP

Reputation: 38

In Windows, if the data you're trying to copy from Excel is in a named range, you could paste it in your Word document using the following bit:

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) #depends on which sheet your named range is located
sheet.Range(NAMED_RANGE_OF_YOUR_TABLE_IN_EXCEL).Copy() 
  
target = doc.Range()
findtext = "WHERE_I_WANT_TO_PASTE_MY_TABLE_IN_WORD" #use a placeholder in your word document where you want the table to appear

if target.Find.Execute(FindText=findtext):
   table_range = doc.Range(Start = target.start, End=target.end)
   table_range.PasteExcelTable(False, False, False)

It will keep the formatting from the workbook.

Upvotes: 1

Related Questions