如何使用pythonCOM从excel复制表 [英] How to copy a table from excel to word using pythonCOM
问题描述
是否可以从excel文件获取表并将其粘贴到保存其excel样式的单词文档中?我没有找到有关win32com及其所有方法的足够文档。
Is it possible to get the table from excel file and paste it to the word document saving its excel style? I didn't find adequate documentation about win32com and all its methods.
我发现了一种方法 PasteExcelTable ,我想我应该选择调用该方法之前从excel的表。我执行以下操作:
I've found a method PasteExcelTable, and I guess I should select the table from excel before invoking this method. I do the following:
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").Select # Selected the table I need to copy
doc.Content.PasteExcelTable(False, False, False)
然后它失败。我甚至不知道我是否走向正确的方向。
And then it fails. I don't even know if I go the right direction.
推荐答案
没有必要选择任何东西,只需直接复制
Got it! There is no need to select anything, just straight copying
sheet.Range("A1:D20").Copy()
doc.Content.PasteExcelTable(False,False,False)
由于没有文档不得不随意尝试一切。
Since there is no documentation I had to try everything at random.
这篇关于如何使用pythonCOM从excel复制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!