0
# Tables
1
2
Comprehensive table creation and manipulation including rows, columns, cells, formatting, and table layout. Provides full control over table structure and appearance.
3
4
## Capabilities
5
6
### Table Creation
7
8
Create tables with specified dimensions and optional styling.
9
10
```python { .api }
11
class Document:
12
def add_table(self, rows, cols, style=None):
13
"""Add a table to the document.
14
15
Args:
16
rows (int): Number of initial rows
17
cols (int): Number of initial columns
18
style (str or TableStyle, optional): Table style name or object
19
20
Returns:
21
Table: New table object
22
"""
23
```
24
25
**Usage Examples:**
26
27
```python
28
# Create basic table
29
table = doc.add_table(rows=3, cols=4)
30
31
# Create table with style
32
styled_table = doc.add_table(rows=2, cols=3, style='Table Grid')
33
34
# Access table cells immediately after creation
35
header_cells = table.rows[0].cells
36
header_cells[0].text = 'Column 1'
37
header_cells[1].text = 'Column 2'
38
header_cells[2].text = 'Column 3'
39
```
40
41
### Table Properties and Methods
42
43
Access and manipulate table structure and properties.
44
45
```python { .api }
46
class Table:
47
def add_row(self):
48
"""Add a row to the end of the table.
49
50
Returns:
51
_Row: New row object
52
"""
53
54
def add_column(self, width):
55
"""Add a column to the right side of the table.
56
57
Args:
58
width (Length): Column width
59
60
Returns:
61
_Column: New column object
62
"""
63
64
def cell(self, row_idx, col_idx):
65
"""Access table cell by row and column indices.
66
67
Args:
68
row_idx (int): Zero-based row index
69
col_idx (int): Zero-based column index
70
71
Returns:
72
_Cell: Cell object at specified position
73
"""
74
75
@property
76
def rows(self):
77
"""Collection of table rows.
78
79
Returns:
80
_Rows: Table rows collection
81
"""
82
83
@property
84
def columns(self):
85
"""Collection of table columns.
86
87
Returns:
88
_Columns: Table columns collection
89
"""
90
91
@property
92
def style(self):
93
"""Table style (read/write).
94
95
Returns:
96
TableStyle or None: Current table style
97
"""
98
99
@style.setter
100
def style(self, value):
101
"""Set table style."""
102
103
@property
104
def alignment(self):
105
"""Table alignment (read/write).
106
107
Returns:
108
WD_TABLE_ALIGNMENT or None: Table alignment
109
"""
110
111
@alignment.setter
112
def alignment(self, value):
113
"""Set table alignment."""
114
115
@property
116
def autofit(self):
117
"""Auto-fit behavior (read/write).
118
119
Returns:
120
bool: True if table auto-fits to content/window
121
"""
122
123
@autofit.setter
124
def autofit(self, value):
125
"""Set auto-fit behavior."""
126
127
@property
128
def table_direction(self):
129
"""Table direction (read/write).
130
131
Returns:
132
WD_TABLE_DIRECTION or None: Text direction in table
133
"""
134
135
@table_direction.setter
136
def table_direction(self, value):
137
"""Set table direction."""
138
```
139
140
**Usage Examples:**
141
142
```python
143
from docx.enum.table import WD_TABLE_ALIGNMENT
144
from docx.shared import Inches
145
146
# Create and modify table
147
table = doc.add_table(rows=2, cols=3)
148
149
# Add rows and columns
150
new_row = table.add_row()
151
new_col = table.add_column(Inches(1))
152
153
# Set table properties
154
table.alignment = WD_TABLE_ALIGNMENT.CENTER
155
table.autofit = False
156
157
# Access specific cells
158
cell = table.cell(0, 1)
159
cell.text = "Cell content"
160
161
# Access via rows/columns
162
table.rows[0].cells[0].text = "Header 1"
163
table.columns[0].width = Inches(2)
164
```
165
166
### Row Operations
167
168
Manipulate table rows including height, formatting, and properties.
169
170
```python { .api }
171
class _Row:
172
@property
173
def cells(self):
174
"""Cells in this row.
175
176
Returns:
177
list[_Cell]: List of cell objects in row
178
"""
179
180
@property
181
def table(self):
182
"""Table containing this row.
183
184
Returns:
185
Table: Parent table object
186
"""
187
188
@property
189
def height(self):
190
"""Row height (read/write).
191
192
Returns:
193
Length or None: Row height
194
"""
195
196
@height.setter
197
def height(self, value):
198
"""Set row height."""
199
200
@property
201
def height_rule(self):
202
"""Row height rule (read/write).
203
204
Returns:
205
WD_ROW_HEIGHT_RULE or None: Height rule setting
206
"""
207
208
@height_rule.setter
209
def height_rule(self, value):
210
"""Set row height rule."""
211
212
class _Rows:
213
def __len__(self):
214
"""Number of rows in table."""
215
216
def __iter__(self):
217
"""Iterate over rows."""
218
219
def __getitem__(self, index):
220
"""Access row by index."""
221
```
222
223
**Usage Examples:**
224
225
```python
226
from docx.shared import Inches
227
from docx.enum.table import WD_ROW_HEIGHT_RULE
228
229
# Access and modify rows
230
table = doc.add_table(rows=3, cols=2)
231
232
# Set row height
233
table.rows[0].height = Inches(0.5)
234
table.rows[0].height_rule = WD_ROW_HEIGHT_RULE.EXACTLY
235
236
# Iterate through rows
237
for i, row in enumerate(table.rows):
238
for j, cell in enumerate(row.cells):
239
cell.text = f"Row {i+1}, Col {j+1}"
240
241
# Access specific row
242
header_row = table.rows[0]
243
for cell in header_row.cells:
244
cell.text = "Header"
245
```
246
247
### Column Operations
248
249
Manipulate table columns including width and formatting.
250
251
```python { .api }
252
class _Column:
253
@property
254
def table(self):
255
"""Table containing this column.
256
257
Returns:
258
Table: Parent table object
259
"""
260
261
@property
262
def width(self):
263
"""Column width (read/write).
264
265
Returns:
266
Length: Column width
267
"""
268
269
@width.setter
270
def width(self, value):
271
"""Set column width."""
272
273
class _Columns:
274
def __len__(self):
275
"""Number of columns in table."""
276
277
def __iter__(self):
278
"""Iterate over columns."""
279
280
def __getitem__(self, index):
281
"""Access column by index."""
282
```
283
284
**Usage Examples:**
285
286
```python
287
from docx.shared import Inches
288
289
# Set column widths
290
table = doc.add_table(rows=2, cols=3)
291
292
table.columns[0].width = Inches(1.5)
293
table.columns[1].width = Inches(2.0)
294
table.columns[2].width = Inches(1.0)
295
296
# Iterate through columns
297
for i, column in enumerate(table.columns):
298
column.width = Inches(1 + i * 0.5)
299
```
300
301
### Cell Operations
302
303
Manipulate individual table cells including content, formatting, and merging.
304
305
```python { .api }
306
class _Cell:
307
def add_paragraph(self, text='', style=None):
308
"""Add a paragraph to the cell.
309
310
Args:
311
text (str, optional): Paragraph text
312
style (str or ParagraphStyle, optional): Paragraph style
313
314
Returns:
315
Paragraph: New paragraph object
316
"""
317
318
def add_table(self, rows, cols):
319
"""Add a nested table to the cell.
320
321
Args:
322
rows (int): Number of initial rows
323
cols (int): Number of initial columns
324
325
Returns:
326
Table: New nested table object
327
"""
328
329
def merge(self, other_cell):
330
"""Merge this cell with another cell.
331
332
Args:
333
other_cell (_Cell): Cell to merge with
334
335
Returns:
336
_Cell: Merged cell object
337
"""
338
339
@property
340
def text(self):
341
"""Cell text content (read/write).
342
343
Setting this replaces all cell content with plain text.
344
"""
345
346
@text.setter
347
def text(self, value):
348
"""Set cell text content."""
349
350
@property
351
def paragraphs(self):
352
"""Paragraphs in the cell.
353
354
Returns:
355
list[Paragraph]: List of paragraph objects
356
"""
357
358
@property
359
def tables(self):
360
"""Nested tables in the cell.
361
362
Returns:
363
list[Table]: List of nested table objects
364
"""
365
366
@property
367
def width(self):
368
"""Cell width (read/write).
369
370
Returns:
371
Length: Cell width
372
"""
373
374
@width.setter
375
def width(self, value):
376
"""Set cell width."""
377
378
@property
379
def vertical_alignment(self):
380
"""Cell vertical alignment (read/write).
381
382
Returns:
383
WD_CELL_VERTICAL_ALIGNMENT or None: Vertical alignment
384
"""
385
386
@vertical_alignment.setter
387
def vertical_alignment(self, value):
388
"""Set cell vertical alignment."""
389
```
390
391
**Usage Examples:**
392
393
```python
394
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
395
from docx.shared import Inches
396
397
# Create table and access cells
398
table = doc.add_table(rows=3, cols=3)
399
400
# Set cell content
401
cell = table.cell(0, 0)
402
cell.text = "Simple text"
403
404
# Add formatted content to cell
405
cell = table.cell(0, 1)
406
para = cell.add_paragraph()
407
run = para.add_run("Bold text")
408
run.bold = True
409
410
# Set cell properties
411
cell.width = Inches(2)
412
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
413
414
# Merge cells
415
top_left = table.cell(0, 0)
416
top_right = table.cell(0, 1)
417
merged_cell = top_left.merge(top_right)
418
merged_cell.text = "Merged cell content"
419
420
# Add nested table
421
cell = table.cell(1, 1)
422
nested_table = cell.add_table(rows=2, cols=2)
423
nested_table.cell(0, 0).text = "Nested"
424
```
425
426
### Table Styling
427
428
Apply and customize table styles and appearance.
429
430
**Usage Examples:**
431
432
```python
433
# Apply built-in table style
434
table = doc.add_table(rows=3, cols=4, style='Light Shading')
435
436
# Available built-in styles include:
437
# 'Table Grid', 'Light Shading', 'Light List', 'Light Grid',
438
# 'Medium Shading 1', 'Medium Grid 1', 'Colorful Grid'
439
440
# Remove table style
441
table.style = None
442
443
# Access table style object for custom formatting
444
if table.style:
445
print(f"Table style: {table.style.name}")
446
```
447
448
### Complex Table Operations
449
450
Advanced table manipulation techniques.
451
452
**Usage Examples:**
453
454
```python
455
# Create table with header row
456
table = doc.add_table(rows=1, cols=4, style='Light Grid')
457
458
# Set up header
459
header_cells = table.rows[0].cells
460
headers = ['Name', 'Age', 'Department', 'Salary']
461
for i, header in enumerate(headers):
462
cell = header_cells[i]
463
cell.text = header
464
# Make header bold
465
cell.paragraphs[0].runs[0].bold = True
466
467
# Add data rows
468
data = [
469
['John Doe', '30', 'Engineering', '$75,000'],
470
['Jane Smith', '25', 'Marketing', '$65,000'],
471
['Bob Johnson', '35', 'Sales', '$70,000']
472
]
473
474
for row_data in data:
475
row_cells = table.add_row().cells
476
for i, value in enumerate(row_data):
477
row_cells[i].text = value
478
479
# Set column widths proportionally
480
total_width = Inches(6)
481
widths = [Inches(1.5), Inches(0.8), Inches(1.2), Inches(1.0)]
482
for i, width in enumerate(widths):
483
table.columns[i].width = width
484
485
# Create table with merged header
486
table = doc.add_table(rows=3, cols=4)
487
488
# Merge top row for title
489
title_cell = table.cell(0, 0).merge(table.cell(0, 3))
490
title_cell.text = "Quarterly Report"
491
title_cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
492
493
# Add sub-headers
494
headers = ['Q1', 'Q2', 'Q3', 'Q4']
495
for i, header in enumerate(headers):
496
table.cell(1, i).text = header
497
```
498
499
## Types
500
501
```python { .api }
502
from docx.enum.table import WD_TABLE_ALIGNMENT
503
504
class WD_TABLE_ALIGNMENT:
505
"""Table alignment options."""
506
LEFT = 0
507
CENTER = 1
508
RIGHT = 2
509
510
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
511
512
class WD_CELL_VERTICAL_ALIGNMENT:
513
"""Cell vertical alignment options."""
514
TOP = 0
515
CENTER = 1
516
BOTTOM = 3
517
518
from docx.enum.table import WD_ROW_HEIGHT_RULE
519
520
class WD_ROW_HEIGHT_RULE:
521
"""Row height rule options."""
522
AUTO = 0
523
AT_LEAST = 1
524
EXACTLY = 2
525
526
from docx.enum.table import WD_TABLE_DIRECTION
527
528
class WD_TABLE_DIRECTION:
529
"""Table text direction options."""
530
LTR = 0 # Left-to-right
531
RTL = 1 # Right-to-left
532
```