The code below is creating a word document with a table but that table does not have borders, yet it is my intention to have a table with borders. Can you help so that the code produces a simple table with borders:
from docx import Document
from docx.shared import Pt
def create_blank_table(word_path, rows, cols):
# Create a new Word document
doc = Document()
# Create a table in Word
table = doc.add_table(rows=rows, cols=cols)
table.autofit = False # Disable autofit to allow setting column widths
# Set column widths
for i in range(cols):
table.columns[i].width = Pt(50) # Adjust the width as needed
# Iterate through cells and set borders with a different color
for row in table.rows:
for cell in row.cells:
set_cell_borders(cell, color='FF0000') # Red color
# Save the Word document
doc.save(word_path)
def set_cell_borders(cell, color='000000'):
# Set cell borders with the specified color
tc_borders = cell._element.xpath('.//w:tcBorders')
if tc_borders:
for border in tc_borders[0]:
border.attrib['w:val'] = 'single'
border.attrib['w:sz'] = '4' # Set border size (adjust as needed)
border.attrib['w:space'] = '0'
border.attrib['w:color'] = color
# Example usage:
create_blank_table(word_path, rows=3, cols=3)