将文本文件附加到word文档Pythondocx中

2024-04-19 09:35:36 发布

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

我正在学习python docx。你知道吗

我不明白如何将.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 有人能帮我做这个吗?你知道吗


Tags: 文件from文档importtxt内容withline
1条回答
网友
1楼 · 发布于 2024-04-19 09:35:36

此代码从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

这项工作将是确保安装了officeinterop(我没有,所以我不能测试)并将脚本重写为Python,这里有一个类似的例子:https://www.daniweb.com/programming/software-development/threads/196521/how-to-insert-or-embed-a-html-file-in-to-a-word-doc

相关问题 更多 >