将文本文件附加到Word文档Python-docx

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

我正在学习python-docx python模块。

我不知道如何将.txt文件附加到Word文档中并保存。

我能够将文件内容写成如下单词。

from docx import Document
document = Document()
with open('textfile.txt') as f:
    for line in f:
        document.add_paragraph(line)
document.save('wordfile.docx')

但是我想附加.txt文件,而不是将内容写到Word中。

预期输出:

enter image description here谁能帮助我做到这一点?

python python-docx
1个回答
0
投票

此代码从Word(VBA)本身完成工作:

Public Function RetrieveOLEInfo(fileExt As String)
    Dim regKey As String
    Dim oleServer As String

    fileExt = "txt"
    regKey = "HKEY_Classes_Root\."
    RetrieveOLEInfo = System.PrivateProfileString("", regKey & fileExt, "")
End Function
Sub Test()
    Documents.Add
    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:=RetrieveOLEInfo("txt"), FileName:="c:\0000\test.txt", LinkToFile:=True, _
        DisplayAsIcon:=True, IconLabel:="test.txt"
End Sub

工作将是确保您安装了Office Interop东西(我没有,所以我无法测试)并将脚本重写为Python,这是在此处执行类似操作的示例:https://www.daniweb.com/programming/software-development/threads/196521/how-to-insert-or-embed-a-html-file-in-to-a-word-doc

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