[英]How to clone/copy .docx file with keeping all styles and alignments using python docx
I want to clone docx file with all of its styles and alignments.我想克隆 docx 文件及其所有 styles 和对齐。 This is my code:这是我的代码:
import docx
from docx import Document
doc = docx.Document('my_word_file.docx')
allText = []
for docpara in doc.paragraphs:
allText.append((docpara.text).replace('a' ,'s')
mydoc = docx.Document()
mydoc.add_paragraph(allText)
mydoc.save("cloned.docx")
So I am fixing some mistakes and file is saving, but without styles or tabs or enters.所以我正在修复一些错误并且文件正在保存,但没有 styles 或制表符或输入。 How to keep changes and stylings too?如何保持变化和样式呢?
I think that the way is to write your own function to copy the text and style of each paragraph.我觉得方法是自己写function来复制每个段落的文字和样式。 Here is a first implementation of what you could do:这是您可以做的第一个实现:
from docx import Document
def copy_paragraph(output_doc, paragraph):
output_paragraph = output_doc.add_paragraph()
# Alignment data of whole paragraph
output_paragraph.paragraph_format.alignment = paragraph.paragraph_format.alignment
for row in paragraph.runs:
output_row = output_paragraph.add_run(row.text)
# Font data
output_row.style.name = row.style.name
# Size of font data
output_row.font.size = row.font.size
# Bold data
output_row.bold = row.bold
# Italic data
output_row.italic = row.italic
# Underline data
output_row.underline = row.underline
# Color data
output_row.font.color.rgb = row.font.color.rgb
doc = Document('my_word_file.docx')
mydoc = Document()
for paragraph in doc.paragraphs:
copy_paragraph(mydoc, paragraph)
mydoc.save("cloned.docx")
I don't exclude that there may be other parameters that need to be copied (for example the highlighting of the text, etc.).我不排除可能还有其他参数需要复制(例如文本的突出显示等)。 In this case I suggest you to do some tests and consult the docx documentation that is pretty well written.在这种情况下,我建议您进行一些测试并查阅写得很好的docx 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.