从列表写入Word文档

时间:2019-07-18 18:42:09

标签: python-3.x tkinter python-docx

我已经编写了一个代码(如下所示),该代码读取一个word文档,并将每个带有格式的“运行”写入列表。这样就创建了一系列格式化的运行,以便以后可以使用部分或全部运行。接下来,我编写了代码,以将所述运行从所述列表写入新文档。问题是我不断收到错误消息,指出““运行”对象不可迭代”。我不知道问题出在用这种方式无法将所有段落信息都写到可以调用的列表中,还是我试图以错误的方式将其写到文档中。

import tkinter as tk
from tkinter.filedialog import askopenfilename
from docx import Document  # Invokes Document command from docx


def get_para_data(output_doc_name, paragraph):
    """
    Write the run to the new file and then set its font, bold, alignment, color etc. data.
    """
    output_run = []
    output_para = output_doc_name.add_paragraph()
    for run in paragraph.runs:
        if paragraph:
            output_run = output_para.add_run(run.text)
            # Run's bold data
            output_run.bold = run.bold
            # Run's italic data
            output_run.italic = run.italic
            # Run's underline data
            output_run.underline = run.underline
            # Run's color data
            output_run.font.color.rgb = run.font.color.rgb
            # Run's font data
            output_run.style.name = run.style.name
            # Paragraph's alignment data
            output_para.paragraph_format.alignment = paragraph.paragraph_format.alignment
        else:
            output_run = []
    return output_run

# IMPORT WORD DOCUMENT
root = tk.Tk()
root.withdraw()
# returns the file path as variable for future use.
doc_path = askopenfilename(title="Choose Word File")
# Imports Word Document to Modify.
document = Document(doc_path)
# Number of paragraphs in document.
t = len(document.paragraphs)
# Preallocation of list.
output_paragraph = [None]*t
result = Document()
# Begin loop to create list of paragraph data using function created above.
i = 0
for para in document.paragraphs:
    output_paragraph[i] = get_para_data(result, document.paragraphs[i])

# Write desired portion of document into a new document.
document_new = Document()
new_line = []
a = 0
for out in output_paragraph:
# Check to Verify it is not a blank line/return.
    if output_paragraph:
        new_line[a] = document_new.add_paragraph(output_paragraph[a])
        a += 1
# if it is a blank line/return write blank line return.
    else:
        document_new.add_paragraph(text='\\r', style=None)
        a += 1

我的预期结果是新文档中的文本与上一个文档中的文本相同,但是我选择的顺序是相同的。与复制和粘贴类似,但我希望能够选择“粘贴”了哪些部分以及何时粘贴。

0 个答案:

没有答案