SoFunction
Updated on 2025-04-27

Code implementation for creating a Word table with border style using Python

introduction

When generating Word documents, the border style of the table is an important detail to improve professionalism. This article will use an example to show how to use itpython-docxLibrary added to tableThicker bordersandInternal borders are hiddencomplex styles. The code will achieve the following effects:

  • The table is at the bottom of the page
  • The upper and lower borders of the first and last rows of the table are thickened
  • Hide the internal horizontal line

Implementation steps

1. Install the dependency library

Make sure it is installedpython-docxLibrary:

pip install python-docx==0.8.10  # It is recommended to use a compatible version

2. Core code analysis

2.1 Define border setting function

from  import OxmlElement
from  import qn

def set_cell_border(cell, **kwargs):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        (tcBorders)

    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = (edge)
        if edge_data:
            tag = f'w:{edge}'
            element = (qn(tag))
            if element is None:
                element = OxmlElement(tag)
                (element)
            
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    (qn(f'w:{key}'), str(edge_data[key]))

Function description

  • passOxmlElementManipulate Word underlying XML
  • Support settingstop/bottomBorders in 6 directions
  • Parameter meaning:
    • sz: Line width (unit: pounds)
    • val:Border type (singleSolid line/noneNo border)
    • color: Hexadecimal color value

2.2 Create a table and set a style

doc = Document()

# Create a table with 3 rows and 1 columnstable = doc.add_table(rows=3, cols=1)
table_rows = 

# Set the style of each cellfor row_id, row in enumerate():
    if row_id == 0:  # First line        for cell in :
            set_cell_border(
                cell,
                top={"sz": 16, "val": "single", "color": "#000000"}, #Bottom border thicker                bottom={"sz": 12, "val": "none"},  # Bottom edge without border                insideH={"sz": 12, "val": "single", "color": "#FFFFF"} # Hide internal lines            )
    elif row_id == 1:  # Intermediate Row        for cell in :
            set_cell_border(
                cell,
                top={"sz": 12, "val": "none"}, 
                bottom={"sz": 12, "val": "single"},
                insideH={"sz": 12, "val": "single", "color": "#FFFFFF"}
            )
    else:  # Last        for cell in :
            set_cell_border(
                cell,
                top={"sz": 12, "val": "none"}, 
                bottom={"sz": 16, "val": "single", "color": "#000000"}, #Back bottom border thicker                insideH={"sz": 12, "val": "single", "color": "#FFFFFF"}
            )

2.3 Control table location

# Push the table to the bottom of the page by paragraph spacingp = doc.add_paragraph()
run = p.add_run('')
p.paragraph_format.space_after = Pt(500)  # Adjust spacing value

Effect display

Generated table style

content Style description
First line Top border is 16 pounds thick, bottom border is transparent
Row in the middle 12 pounds of solid line on the upper and lower borders, hidden internal lines
The last line Lower border 16 pounds thick

Things to note

  1. Border logic

    • insideHControl the horizontal line between rows
    • By settingcolorIt can hide the internal lines in white
    • Bolding effect is increased by enlargingszValue implementation
  2. Version compatibility

    • Recommended usepython-docx==0.8.10Version
    • The import path may need to be adjusted for higher versions:
from  import OxmlElement  # 0.8.11+ version
  • Table positioning skills

    • By enlargementspace_afterParagraph spacing implementation
    • More precise bottom alignment requires using section breaks to set the page margin (see the code at the beginning of this article)

Complete code

# See the code example at the beginning of this article for the complete code# Save and run: python your_script.py

Extended reading

  • python-docx official documentation
  • Word XML format reference

Through the implementation of this article, you can quickly master:

  • The underlying XML operation skills of Word tables
  • Programmatic implementation of complex border styles
  • Layout control method for document elements

This article combines code functions, implementation principles and precautions, and is suitable for Python developers to quickly access watch style settings. For further optimization, you can add:

  • Document section breaks achieve accurate bottom alignment
  • How to add picture seals
  • Complete implementation of header and footer

I hope this article can help you improve your Python document processing capabilities!

from docx import Document
from  import Pt
from  import OxmlElement
from  import qn


def set_cell_border(cell, **kwargs):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        (tcBorders)

    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = (edge)
        if edge_data:
            tag = 'w:{}'.format(edge)
            element = (qn(tag))
            if element is None:
                element = OxmlElement(tag)
                (element)

            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    (qn('w:{}'.format(key)), str(edge_data[key]))


doc = Document()

# Add some text as placeholdersp = doc.add_paragraph()
run = p.add_run('')
 = Pt(12)

# Increase the spacing behind paragraphs to try to push the next table to the bottom of the pagep.paragraph_format.space_after = Pt(500)  # Adjust this value to suit different page sizes and content volumes
# Create and add a tabletable = doc.add_table(rows=3, cols=1)
hdr_cells = [0].cells
hdr_cells[0].text = 'Give it: zone.  '
hdr_cells = [1].cells
hdr_cells[0].text = 'hair:.  '
hdr_cells = [2].cells
hdr_cells[0].text = 'hair'

# Set the border of each cellfor row_id, row in enumerate():
    if row_id == 0:

        for cell in :
            set_cell_border(
                cell,
                top={"sz": 16, "val": "single", "color": "#000000"}, # Black solid line border                bottom={"sz": 12, "val": "none", },  # Black solid line under border                start={"sz": 0, "val": "none"},  # left border without border                end={"sz": 0, "val": "none"},  # Right border without border                insideH={"sz": 12, "val": "single", "color": "#FFFFFF"}, # Set the internal horizontal line color to white (or select another color to match the background)            )
    elif row_id == 1:
        for cell in :
            set_cell_border(
                cell,
                top={"sz": 12, "val": "none", },  # Black solid line border                bottom={"sz": 12, "val": "single", "color": "#000000"},  # Black solid line under border                start={"sz": 0, "val": "none"},  # left border without border                end={"sz": 0, "val": "none"},  # Right border without border                insideH={"sz": 12, "val": "single", "color": "#FFFFFF"}, # Set the internal horizontal line color to white (or select another color to match the background)            )
    else:
        for cell in :
            set_cell_border(
                cell,
                top={"sz": 12, "val": "none"},  # Black solid line border                bottom={"sz": 16, "val": "single", "color": "#000000"},  # Black solid line under border                start={"sz": 0, "val": "none"},  # left border without border                end={"sz": 0, "val": "none"},  # Right border without border                insideH={"sz": 12, "val": "single", "color": "#FFFFFF"}, # Set the internal horizontal line color to white (or select another color to match the background)            )

('')

The above is the detailed content of the code implementation of using Python to create a Word table with border style. For more information about creating a Word table with borders in Python, please pay attention to my other related articles!