- Specify border appearance in tables using python-docx
- Advertisement
- Answer
- Table objects¶
- Table objects¶
- _Cell objects¶
- _Row objects¶
- _Column objects¶
- _Rows objects¶
- _Columns objects¶
- Table of Contents
- How to setup cell borders with python-docx?
- Method 1: Using the ‘_Element.add_border’ method
- Method 2: Using the ‘_Element.style’ property
- Method 3: Using the ‘python-docx-template’ library
- How to add table border to word doc using python docx
Specify border appearance in tables using python-docx
I am going through the tutorial and documentation of python-docx.
However, I can’t find any reference to how I can specify and manipulate the border appearance of a table created in a Microsoft Word document.
When i use the following code:
from docx import Document from docx.shared import Inches document = Document() ################################ ################################ ################################ table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' row_cells = table.add_row().cells row_cells[0].text = 'Str0' row_cells[1].text = 'Str1' row_cells[2].text = 'Str2' row2_cells = table.add_row().cells row2_cells[0].text = 'Str00' row2_cells[1].text = 'Str11' row2_cells[2].text = 'Str22' ################################ ################################ ################################ document.save('demo.docx')
The resulting docx file shows the 3×3 table with header. Currently there is no black border (inner or outer) on this table.
How can I specify an upper and lower border around the header, a lower border to wrap around the table, as well as an inner vertical border?
Advertisement
Answer
Unfortunately, there is no way to directly manipulate table borders from within python-docx . You basically need to use a style, which specifies these. The style must already exist in Word.
In order to generate a table style to your liking, you need to manually create a new empty document in Word, customize one of the existing table styles there (e.g. Colorful Shading ), and add a table using this modified style. Next, you delete this table and save the file (say example.docx ) on your disk. This is necessary for the modified style to be saved in the document.
All you have to do then is load the file using python-docx and add a new table, which will reference the (modified) table style:
document = Document('example.docx') table = document.add_table(rows=1, cols=3) table.style = 'ColorfulShading'
See also Understanding styles in the documentation for details on how styles in Word work.
Table objects¶
Table objects are constructed using the add_table() method on Document .
Table objects¶
Proxy class for a WordprocessingML element.
Return a _Column object of width, newly added rightmost to the table.
Return a _Row instance, newly added bottom-most to the table.
Read/write. A member of WD_TABLE_ALIGNMENT or None, specifying the positioning of this table between the page margins. None if no setting is specified, causing the effective value to be inherited from the style hierarchy.
True if column widths can be automatically adjusted to improve the fit of cell contents. False if table layout is fixed. Column widths are adjusted in either case if total column width exceeds page width. Read/write boolean.
Return _Cell instance correponding to table cell at row_idx, col_idx intersection, where (0, 0) is the top, left-most cell.
Sequence of cells in the column at column_idx in this table.
_Columns instance representing the sequence of columns in this table.
Sequence of cells in the row at row_idx in this table.
_Rows instance containing the sequence of rows in this table.
Read/write. A _TableStyle object representing the style applied to this table. The default table style for the document (often Normal Table ) is returned if the table has no directly-applied style. Assigning None to this property removes any directly-applied table style causing it to inherit the default table style of the document. Note that the style name of a table style differs slightly from that displayed in the user interface; a hyphen, if it appears, must be removed. For example, Light Shading — Accent 1 becomes Light Shading Accent 1 .
A member of WD_TABLE_DIRECTION indicating the direction in which the table cells are ordered, e.g. WD_TABLE_DIRECTION.LTR . None indicates the value is inherited from the style hierarchy.
_Cell objects¶
Return a paragraph newly added to the end of the content in this cell. If present, text is added to the paragraph in a single run. If specified, the paragraph style style is applied. If style is not specified or is None , the result is as though the ‘Normal’ style was applied. Note that the formatting of text in a cell can be influenced by the table style. text can contain tab ( \t ) characters, which are converted to the appropriate XML form for a tab. text can also include newline ( \n ) or carriage return ( \r ) characters, each of which is converted to a line break.
Return a table newly added to this cell after any existing cell content, having rows rows and cols columns. An empty paragraph is added after the table because Word requires a paragraph element as the last element in every cell.
Return a merged cell created by spanning the rectangular region having this cell and other_cell as diagonal corners. Raises InvalidSpanError if the cells do not define a rectangular region.
List of paragraphs in the cell. A table cell is required to contain at least one block-level element and end with a paragraph. By default, a new cell contains a single paragraph. Read-only
List of tables in the cell, in the order they appear. Read-only.
The entire contents of this cell as a string of text. Assigning a string to this property replaces all existing content with a single paragraph containing the assigned text in a single run.
A value of None indicates vertical alignment for this cell is inherited. Assigning None causes any explicitly defined vertical alignment to be removed, restoring inheritance.
The width of this cell in EMU, or None if no explicit width is set.
_Row objects¶
Sequence of _Cell instances corresponding to cells in this row.
Return a Length object representing the height of this cell, or None if no explicit height is set.
Return the height rule of this cell as a member of the WD_ROW_HEIGHT_RULE enumeration, or None if no explicit height_rule is set.
Reference to the Table object this row belongs to.
_Column objects¶
Sequence of _Cell instances corresponding to cells in this column.
Reference to the Table object this column belongs to.
The width of this column in EMU, or None if no explicit width is set.
_Rows objects¶
Sequence of _Row objects corresponding to the rows in a table. Supports len() , iteration, indexed access, and slicing.
Reference to the Table object this row collection belongs to.
_Columns objects¶
Sequence of _Column instances corresponding to the columns in a table. Supports len() , iteration and indexed access.
Reference to the Table object this column collection belongs to.
Table of Contents
How to setup cell borders with python-docx?
python-docx is a Python library for creating and updating Microsoft Word (.docx) files. It allows developers to programmatically create, edit and extract information from Word documents. One of the features that python-docx provides is the ability to work with tables in a Word document. However, sometimes it can be difficult to figure out how to format the tables in the way you want, such as adding cell borders. In this article, we will explore different methods for adding cell borders to tables created with python-docx.
Method 1: Using the ‘_Element.add_border’ method
To set up cell borders with python-docx using the ‘_Element.add_border’ method, you can follow these steps:
from docx import Document from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Pt
document = Document() table = document.add_table(rows=3, cols=3)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
cell = table.cell(0, 0) cell.text = 'Cell 1' cell = table.cell(0, 1) cell.text = 'Cell 2' cell = table.cell(0, 2) cell.text = 'Cell 3'
cell = table.cell(0, 0) cell._element.add_border(top='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(left='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(bottom='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(right='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell = table.cell(0, 1) cell._element.add_border(top='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(bottom='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(right='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell = table.cell(0, 2) cell._element.add_border(top='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(bottom='sz': Pt(2), 'val': 'single', 'color': '000000'>) cell._element.add_border(right='sz': Pt(2), 'val': 'single', 'color': '000000'>)
This code will add a table with three cells and set the borders of the cells using the ‘_Element.add_border’ method. You can modify the code to add more cells and set different borders for each cell.
Method 2: Using the ‘_Element.style’ property
To set up cell borders using the _Element.style property in python-docx, you can follow these steps:
from docx import Document from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document() table = document.add_table(rows=3, cols=3)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
cell._element.style = ( 'border-top: 1px solid black; ' 'border-bottom: 1px solid black; ' 'border-left: 1px solid black; ' 'border-right: 1px solid black;' )
Here’s an example code that sets up borders for all cells in the table:
from docx import Document from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH document = Document() table = document.add_table(rows=3, cols=3) table.alignment = WD_TABLE_ALIGNMENT.CENTER for row in table.rows: for cell in row.cells: cell._element.style = ( 'border-top: 1px solid black; ' 'border-bottom: 1px solid black; ' 'border-left: 1px solid black; ' 'border-right: 1px solid black;' ) document.save('example.docx')
This code sets up borders for all cells in the table by looping through each row and cell and setting the border style using the _Element.style property. The resulting document is saved as «example.docx».
Method 3: Using the ‘python-docx-template’ library
To set up cell borders in a table using the ‘python-docx-template’ library, follow these steps:
from docxtpl import DocxTemplate, Table from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = DocxTemplate("template.docx")
table.alignment = WD_TABLE_ALIGNMENT.CENTER
for row in table.rows: for cell in row.cells: for paragraph in cell.paragraphs: paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER borders = cell._element.xpath('.//w:tcBorders')[0] borders.top.color = 'auto' borders.top.sz = 6 borders.top.space = 0 borders.bottom.color = 'auto' borders.bottom.sz = 6 borders.bottom.space = 0 borders.left.color = 'auto' borders.left.sz = 6 borders.left.space = 0 borders.right.color = 'auto' borders.right.sz = 6 borders.right.space = 0
This code sets the alignment of the table to center and sets the borders of each cell to have a size of 6 and no space. The borders are set to be the same color as the text in the cell. This code can be modified to set the borders to different sizes, colors, and spaces.
How to add table border to word doc using python docx
I’m trying to create a word document using docx module of Python. However I am unable to add table border to it. My code is as below:
import docx from docx import Document from docx.shared import Pt doc = Document('C:/Users/Vinny/Desktop/Python/Template.docx') doc.add_paragraph('Changes:') doc.add_paragraph('Metrics:') #add table table = doc.add_table(rows = 4, cols = 2, style='TableGrid') doc.save('C:/Users/Vinny/Desktop/Python/rel.docx')
Traceback (most recent call last): File "C:\Users\Vinny\Desktop\Python\abc.py", line 14, in table = doc.add_table(rows = 4, cols = 2, style='TableGrid') File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\document.py", line 100, in add_table table.style = style File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\table.py", line 134, in style style_or_name, WD_STYLE_TYPE.TABLE File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\parts\document.py", line 76, in get_style_id return self.styles.get_style_id(style_or_name, style_type) File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 113, in get_style_id return self._get_style_id_from_name(style_or_name, style_type) File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 143, in _get_style_id_from_name return self._get_style_id_from_style(self[style_name], style_type) File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 57, in __getitem__ raise KeyError("no style with name '%s'" % key) KeyError: "no style with name 'TableGrid'"