【问题标题】:I want to convert .docx to .dotx我想将 .docx 转换为 .dotx
【发布时间】:2022-04-28 22:51:27
【问题描述】:

我在 .docx 文件中填充了一些邮件合并字段,现在我希望我的脚本将保存的 .docx 文件转换为 .dotx 文件。我正在使用 Python 3.6。

from __future__ import print_function
from mailmerge import MailMerge
from datetime import date
from docx import Document
from docx.opc.constants import CONTENT_TYPE as CT
import csv
import sys
import os
import numpy as np
import pandas as pd

# . . .

for i in range(0, numTemplates):
   theTemplateName = templateNameCol[i]
   theTemplateFileLocation = templateFileLocationCol[i]
   template = theTemplateFileLocation
   document = MailMerge(template)
   print(document.get_merge_fields())

   theOffice = officeCol[i]
   theAddress = addressCol[i]
   theSuite = suiteCol[i]
   theCity = cityCol[i]
   theState = stateCol[i]
   theZip = zipCol[i]
   thePhoneNum = phoneNumCol[i]
   theFaxNum = faxNumCol[i]

   document.merge(
       Address = theAddress 
   )

   document.write(r'\Users\me\mailmergeproject\test-output' + str(i) + r'.docx')
   #do conversion here

底部是我要进行转换的地方。如您所见,我已经编写了一个文件,它现在只是放在一个文件夹中

【问题讨论】:

  • 如果你想写一个.dotx而不是.docx,改变那个扩展名!尽管公平地告诉您:如果您这样做并再次运行您的程序,.dotx 文件将只是放在一个文件夹中而什么都不做。我并不完全清楚你期望它做什么。
  • 我已经尝试过更改扩展名 - 它会引发错误,而在写入 .docx 时却不会

标签: python ms-word docx file-conversion


【解决方案1】:

这里是将.docx文件转换为dotx的代码sn-p。 您必须在保存文档时更改内容类型

pip install python-docx

import docx

document = docx.Document('foo.dotx')
document_part = document.part
document_part._content_type = 'application/vnd.openxmlformats- 
                              officedocument.wordprocessingml.template.main+xml'
document.save('bar.docx')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多