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
Working with tables in Python-Docx
For complete list of table styles, view on python-docx.
Create Table
Lets Create a table with 2 rows and 2 colums using add_table method. Table style can be defined using style argument which in this case is Table Grid.
from docx import Document # create document doc = Document() # add grid table table = doc.add_table(rows=2, cols=2, style="Table Grid")
Now table rows and columns can be accessed using table.rows or table.columns attribute respectively and then we can access each cell in that row using row.cells . Lets add headings to 1st row.
# access first row's cells heading_row = table.rows[0].cells # add headings heading_row[0].text = "Name" heading_row[1].text = "Marks"
Same way we can add other info to rows
# access second row's cells data_row = table.rows[1].cells # add headings data_row[0].text = "Ali" data_row[1].text = "68"
We can also add rows after table creation using add_row method which adds a row in table and we can add data to that row.
# add new row to table data_row = table.add_row().cells # add headings data_row[0].text = "Bilal" data_row[1].text = "26"
It creates a table with 3 rows and 2 columns with information.
Cell Margin
We can use OpenXML to modify and set any style using python-docx. Here we can specify margin to any cell where we can add or completely remove a cell margin.
from docx.oxml.shared import OxmlElement from docx.oxml.ns import qn 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)
Now we can add margin in any cell to increase space.
# access second row's cells data_row = table.add_row().cells set_cell_margins(data_row[0], top=100, start=100, bottom=100, end=50) # add headings data_row[0].text = "Usman" data_row[1].text = "76"
Nested Table
We can also created nested tables where we can add a table to a cell. For example, if for 1 person, we want to add marks for multiple subjects. We can add a table to parent table cells.
marks = # add new row data_row = table.add_row().cells # name of person data_row[0].text = "Nasir" # We add a table to 2nd cell with rows equal to our entries (3) marks_table = data_row[1].add_table(rows=len(marks), cols=2)
Now we can iterate over values and add to table.
for i, row in enumerate(marks.items()): # iterate over 3 values marks_table.rows[i].cells[0].text = row[0] # sub table first cell marks_table.rows[i].cells[1].text = str(row[1]) # second cell
We can also show images inside tables.
Table Images
In table paragraphs, we can add images to table. Here is a simple example to add two images to table. Here we get paragraph for a cell where we want to display image and then use add_picture method to add an image from path. and we also specify height and width in Inches.
from docx.shared import Inches, Cm doc = Document() # create doc doc.add_heading('Images in Table', 0) # add heading # create table with two rows and columns table = doc.add_table(rows=2, cols=2, style="Table Grid") # add first image with text table.rows[0].cells[0].text = 'This is image text inside table for 1st image.' # add image to table paragraph = table.rows[0].cells[1].paragraphs[0] run = paragraph.add_run() run.add_picture('image-1.jpg', width=Inches(3), height=Inches(1.5)) table.rows[1].cells[0].text = 'This is image text inside table for 2nd image.' # add image to table paragraph = table.rows[1].cells[1].paragraphs[0] run = paragraph.add_run() run.add_picture('image-2.jpg', width=Inches(3), height=Inches(1.5)) # save to file doc.save("images-table.docx")
So it creates a table with text in 1st column and images in 2nd column for each row.
For more info to working with images, view my next post or view python-docx documentation.
View can add data from csv file, text file or any other file to tables in docx. So for more info view python docx documentation.