我正在学习 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中。
预期输出:
答案 0 :(得分: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