如何使用python在word文档中的特定段落后添加表格

问题描述 投票:0回答:1

我尝试用 python 在 docx 中写一个表。目前该表放置在文档的末尾,但我想放置在段落[85]之后。我使用的Word文档里面已经充满了数据,比如平面文本或表格。选取要写入 docx 的表格来自 Excel 文件(按预期工作)。主要问题和写表的地方有关

def set_cell_margins(cell, **kwargs):
    """
    cell:  actual cell instance you want to modify
    usage:
        set_cell_margins(cell, top=50, start=50, bottom=50, end=50)

    provided values are in twentieths of a point (1/1440 of an inch).
    read more here: http://officeopenxml.com/WPtableCellMargins.php
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')

    for m in ["top", "start", "bottom", "end"]:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            node.set(qn('w:w'), str(kwargs.get(m)))
            node.set(qn('w:type'), 'dxa')
            tcMar.append(node)

    tcPr.append(tcMar)


def add_table_to_doc(document, df, heading, table_style='Table Grid'):
    """ Adds a table to a docx document """
    columns = list(df.columns)
    # add table
    table = document.add_table(rows=1, cols=len(columns), style=table_style)
    table.autofit = True
    # add columns if there is '_' then replace with space
    for col in range(len(columns)):
        set_cell_margins(table.cell(0, col), top=50, start=50, bottom=50, end=50)
        table.cell(0, col).text = columns[col].replace("_", " ").capitalize()
    # add data
    for i, row in enumerate(df.itertuples()):
        table_row = table.add_row().cells
        for col in range(len(columns)):
            set_cell_margins(table_row[col], top=50, start=50, bottom=50, end=50)
            table_row[col].text = str(row[col + 1])

    doc.add_paragraph("\n")
# Store in doc variable what is inside of this document
doc = docx.Document(path_to_docx)
# Write in release document the table with integrated tickets
hr_df = pd.read_excel(latest_file, engine="openpyxl")
hr_df = hr_df[['id', 'summary']]

text = "Changelog  " + lines[0] + " (Integrated CRs):"
add_text(doc, text + "\n\n")

add_table_to_doc(doc, hr_df.iloc[:100], 'test')
print(latest_file)

doc.save(path_to_docx)
doc.add_paragraph("\n")
python python-3.x scripting python-3.6 docx
1个回答
0
投票

看起来您想使用Python-docx将表格插入到Word文档中的特定位置。为此,您可以使用

insert_paragraph_before
方法在所需位置之前添加一个段落(在本例中为在 paragraph[85] 之前),然后将表格添加到新插入的段落中。这是对代码的修改示例:

import docx
import pandas as pd
from docx.oxml import OxmlElement
from docx.shared import Pt
from docx.oxml.ns import qn

def set_cell_margins(cell, **kwargs):
    # ... (your existing set_cell_margins function)

def add_table_to_doc(document, df, heading, table_style='Table Grid'):
    # ... (your existing add_table_to_doc function)

# Load existing document
doc = docx.Document(path_to_docx)

# Insert a new paragraph before paragraph[85]
target_paragraph_index = 85
new_paragraph = doc.add_paragraph("\n")
doc.paragraphs.insert(target_paragraph_index, new_paragraph)

# Write in the release document the table with integrated tickets after the new paragraph
hr_df = pd.read_excel(latest_file, engine="openpyxl")
hr_df = hr_df[['id', 'summary']]

text = "Changelog  " + lines[0] + " (Integrated CRs):"
add_text(doc, text + "\n\n")

add_table_to_doc(new_paragraph, hr_df.iloc[:100], 'test')  # Use the new_paragraph as the target
print(latest_file)

# Save the modified document
doc.save(path_to_docx)

此修改在段落[85]之前插入一个新段落,然后使用该段落作为添加表格的目标。根据文档的实际结构根据需要调整

target_paragraph_index

© www.soinside.com 2019 - 2024. All rights reserved.