问题描述
我有一个使用 python-docx 创建 docx 文件的 python 脚本。文档文件的超链接设置为链接到文档段落内的书签。如果我在笔记本电脑中打开文档,它会正确显示。但是当我上传后在谷歌驱动器上打开文档时,它跳过了超链接部分。任何想法可能会出错?这就是我使用 pydrive 上传文档的方式。如果有帮助,我应该尝试以 PDF 格式上传吗?
http = drive.auth.Get_Http_Object()
# createfile
file1 = drive.CreateFile({'title': 'Test Report.docx','mimeType': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'})
file1.SetContentFile("read.docx")
file1.Upload(param={"http": http})
解决方法
找到了无需打开 Word 文档即可执行此操作的正确方法。它需要安装 PyWin32 库。
import win32com.client
def update_toc(file):
word = win32com.client.DispatchEx("Word.Application")
print(os.path.join(os.getcwd(),file))
doc = word.Documents.Open(os.path.join(os.getcwd(),file))
doc.TablesOfContents(1).Update()
word.ActiveDocument.Fields.Update()
doc.Close(SaveChanges=True)
word.Application.Quit()