Hello I am new users of Jupyter python and I have a question:
I have data in xls sheet and I want to write some of the columns in words docx by using python.
I have 12 columns and I want only 3 in docx file.
Advertisement
Answer
In Windows, name the range of the 3 columns you’re trying to copy in Excel. You can then paste it in your Word document using the following bit:
JavaScript
x
18
18
1
from win32com import client
2
3
excel = client.Dispatch("Excel.Application")
4
word = client.Dispatch("Word.Application")
5
6
doc = word.Documents.Open("C:/word_file.docx")
7
book = excel.Workbooks.Open("C:/excel_file.xlsx")
8
9
sheet = book.Worksheets(1) #depends on which sheet your named range is located
10
sheet.Range(NAMED_RANGE_OF_YOUR_TABLE_IN_EXCEL).Copy()
11
12
target = doc.Range()
13
findtext = "WHERE_I_WANT_TO_PASTE_MY_TABLE_IN_WORD" #use a placeholder in your word document where you want the table to appear
14
15
if target.Find.Execute(FindText=findtext):
16
table_range = doc.Range(Start = target.start, End=target.end)
17
table_range.PasteExcelTable(False, False, False)
18
It will keep the formatting from the workbook.