简体   繁体   English

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

[英]Attaching text file into word document Python-docx

I am learning python-docx python module.我正在学习python-docx python 模块。

I am not getting how I could attach a .txt file into word document and save it.我不知道如何将.txt文件附加到 Word 文档中并保存。

I am able to write file content into a word like below.我能够将文件内容写入如下所示的单词。

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

But I want to attach .txt file instead of writing content into word.但我想附加.txt文件而不是将内容写入 word。

Expected output:预期输出:

在此处输入图片说明 Can anyone help me to do this?谁能帮我做到这一点?

This code does the job from Word (VBA) itself:此代码从 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

The job would be to make sure you have Office Interop stuff installed (I don't, so I can't test) and rewrite the script into Python, an examples of someone doing something similar here: https://www.daniweb.com/programming/software-development/threads/196521/how-to-insert-or-embed-a-html-file-in-to-a-word-doc工作是确保您安装了 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM