使用win32com和Python将Excel数据粘贴到特定的MS Word段落中。

问题描述 投票:1回答:1

我想复制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()
python excel ms-word pywin32 win32com
1个回答
0
投票

要折叠到结尾而不是开头的任何地方 Range:

# Paste Excel data at the end of the doc, while keeping doc data
wdRange.Collapse(0)

注:要想看到这类信息,请启动Word。按Alt+F11打开VBA编辑器,然后按F2启动对象浏览器。如果你再输入,例如 Collapse 到搜索框中,然后你可以点击它,按F1键得到帮助主题。

你还会看到,在结果列表中,再往下,还有一个条目是 WdCollapseDirection的值,它将显示可以传递给 Collapse 方法。点击该方法,底部列表中会出现两个枚举。点击其中一个,然后在最下面的窗格中查看你的代码所需要的数值(0或1)。

© www.soinside.com 2019 - 2024. All rights reserved.