如何从excel自动复制数据并粘贴到word中?

2024-09-27 21:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾尝试将docxtpl与Python结合使用,但返回的结果非常难看,根本不可读。我尝试使用数据帧、列表。。。但在我看来,我没有一张干净的桌子。有人知道如何使用Python吗?还是使用VBA更简单

(docx不允许我在单词中添加我想要的表。) 使用Dataframe时,表是trounce。对于列表,列不适合

非常感谢

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)

其中para_multiple是一个包含.doc和liste_数据框中所有标记的列表,数据框列表包含我在文档上需要的数据

(这是我现在得到的,我不知道如何正确显示) 我需要删除表格和索引

https://i.stack.imgur.com/r3CQJ.png


Tags: 数据dataframe列表doccontextmultiplevba单词
1条回答
网友
1楼 · 发布于 2024-09-27 21:29:09

在Windows中,如果试图从Excel复制的数据位于命名范围内,则可以使用以下位将其粘贴到Word文档中:

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)

它将保留工作簿中的格式设置

相关问题 更多 >

    热门问题