[Python] Issue with Populating Word Table from Pandas DataFrame

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    Problem: The Word table generated from a filtered Pandas DataFrame appears empty, even though the DataFrame (df_filtered) contains valid data. The main issue seems to be that the text is not being written into the Word table cells due to incorrect handling of cell content or issues with paragraph and run initialization within each cell.

    # === Populate Table 2 ===
    # === Create the table with data from df_filtered ===
    table = doc.add_table(rows=df_filtered.shape[0] + 1, cols=len(columns_to_display))
    table.style = 'Table Grid'

    # === Table header ===
    header_cells = table.rows[0].cells
    for i, col_name in enumerate(columns_to_display):
    header_cells.text = col_name # Add the header text
    header_paragraph = header_cells.paragraphs[0]
    header_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    header_run = header_paragraph.runs[0]
    header_run.font.name = 'Arial'
    header_run.font.size = Pt(11)
    header_run.font.bold = True

    # === Fill the table ===
    for i, row in df_filtered.iterrows():
    for j, value in enumerate(row):
    # Ensure each cell has a valid paragraph
    cell = table.cell(i + 1, j)
    cell.text = str(value) if pd.notnull(value) else ''
    cell_paragraph = cell.paragraphs[0]
    cell_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT

    # Set the font for each cell
    cell_run = cell_paragraph.runs[0]
    cell_run.font.name = 'Arial'
    cell_run.font.size = Pt(10)[enter image description here](https://i.sstatic.net/82I19HCT.jpg)


    enter image description here

    Continue reading...

Compartilhe esta Página