[英]Paste Excel data in specific MS Word paragraph using win32com and Python
我想復制 Excel 數據(例如表格或特定范圍)並將其粘貼到 MS Word 文檔段落的末尾而不替換其文本。 上述過程應使用 Python 完成,最好使用 pywin32 (win32com.client)。
下面的代碼效果很好,但是 Excel 數據只能粘貼在 Word 文檔的開頭:
def copy_from_excel_paste_to_word(word_filename, excel_filename):
# Word init
word = client.Dispatch("Word.Application")
word.Visible = True
report = word.Documents.Open(word_path)
wdRange = report.Content
# Excel init
excel = client.Dispatch("Excel.Application")
checklist = excel.Workbooks.Open(excel_path)
sheet = checklist.Worksheets("Names")
sheet.Range("B2:D15").Copy()
# Paste Excel data at the beginning of the doc, while keeping doc data
wdRange.Collapse(1)
wdRange.PasteExcelTable(False, False, False) # ? How can i specify the paste location ?
# Save and quit
word.ActiveDocument.Close(SaveChanges=True)
excel.Quit()
word.Quit()
折疊到末尾而不是任何Range
的開頭:
# Paste Excel data at the end of the doc, while keeping doc data
wdRange.Collapse(0)
注意:要查看此類信息,請啟動 Word。 按 Alt+F11 打開 VBA 編輯器,然后按 F2 啟動 Object 瀏覽器。 例如,如果您在搜索框中鍵入“ Collapse
”,您可以單擊它並按 F1 以獲取幫助主題。
您還將在結果列表的下方看到條目WdCollapseDirection
,它將顯示可以傳遞給Collapse
方法的值。 單擊它,兩個枚舉將出現在底部列表中。 單擊一個,然后在最底部的窗格中查看代碼所需的數值(0 或 1)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.