0
# Tables and Tabular Data
1
2
Comprehensive table creation with various table types, formatting options, and cell manipulation capabilities. PyLaTeX provides a rich set of classes for creating professional-looking tables with support for multi-column layouts, long tables, and advanced styling.
3
4
## Capabilities
5
6
### Basic Tabular Environment
7
8
The Tabular class is the foundation for creating tables in LaTeX, providing precise control over column specifications and content.
9
10
```python { .api }
11
class Tabular(Environment):
12
def __init__(self, table_spec, data=None, pos=None, *,
13
row_height=None, col_space=None, width=None,
14
booktabs=None, **kwargs):
15
"""
16
Create a basic tabular environment.
17
18
Parameters:
19
- table_spec: str, column specification ('lrc', 'p{3cm}', etc.)
20
- data: list, initial table data
21
- pos: list, vertical positioning options
22
- row_height: float, relative row height multiplier
23
- col_space: str, spacing between columns
24
- width: int, number of columns (auto-calculated if None)
25
- booktabs: bool, use professional-style booktabs formatting
26
"""
27
28
def add_row(self, *cells, color=None, escape=None,
29
mapper=None, strict=True):
30
"""
31
Add a row to the table.
32
33
Parameters:
34
- *cells: content for each cell in the row
35
- color: str, row background color
36
- escape: bool, escape special LaTeX characters
37
- mapper: callable, function to map cell content
38
- strict: bool, enforce column count matching
39
"""
40
41
def add_hline(self, start=None, end=None, *, color=None):
42
"""
43
Add horizontal line across table.
44
45
Parameters:
46
- start: int, starting column (1-indexed)
47
- end: int, ending column (1-indexed)
48
- color: str, line color
49
"""
50
51
def add_multicolumn(self, size, align, content, *, cells=None):
52
"""
53
Add multi-column cell to current row.
54
55
Parameters:
56
- size: int, number of columns to span
57
- align: str, column alignment ('l', 'c', 'r')
58
- content: str or LatexObject, cell content
59
- cells: list, additional cells for the row
60
"""
61
62
def add_multirow(self, size, align, content, *, hlines=True,
63
cells=None, color=None):
64
"""
65
Add multi-row cell to table.
66
67
Parameters:
68
- size: int, number of rows to span
69
- align: str, column alignment
70
- content: str or LatexObject, cell content
71
- hlines: bool, add horizontal lines
72
- cells: list, additional cells
73
- color: str, cell background color
74
"""
75
```
76
77
Usage example:
78
79
```python
80
from pylatex import Document, Tabular, Command
81
from pylatex.table import MultiColumn, MultiRow
82
83
doc = Document()
84
85
# Basic table
86
with doc.create(Tabular('|c|c|c|')) as table:
87
table.add_hline()
88
table.add_row(('Name', 'Age', 'City'))
89
table.add_hline()
90
table.add_row(('Alice', 25, 'New York'))
91
table.add_row(('Bob', 30, 'London'))
92
table.add_hline()
93
94
# Table with booktabs styling
95
geometry_options = {"margin": "1in"}
96
doc = Document(geometry_options=geometry_options)
97
98
with doc.create(Tabular('lcc', booktabs=True)) as table:
99
table.add_row(['Product', 'Price', 'Quantity'])
100
table.add_hline()
101
table.add_row(['Widget A', '$10.99', '50'])
102
table.add_row(['Widget B', '$15.99', '30'])
103
```
104
105
### Table Float Environment
106
107
The Table class creates floating table environments that can be positioned automatically by LaTeX.
108
109
```python { .api }
110
class Table(Float):
111
def __init__(self, position=None, **kwargs):
112
"""
113
Create a floating table environment.
114
115
Parameters:
116
- position: str, float positioning ('h', 't', 'b', 'p', '!')
117
"""
118
```
119
120
Usage example:
121
122
```python
123
from pylatex import Document, Section, Tabular
124
from pylatex.table import Table
125
from pylatex import Command
126
127
doc = Document()
128
129
with doc.create(Section('Sales Data')):
130
with doc.create(Table(position='htbp')) as table:
131
table.add_caption('Quarterly Sales Report')
132
133
with table.create(Tabular('|l|c|c|c|')) as tabular:
134
tabular.add_hline()
135
tabular.add_row(['Quarter', 'Revenue', 'Profit', 'Growth'])
136
tabular.add_hline()
137
tabular.add_row(['Q1', '$100K', '$20K', '5%'])
138
tabular.add_row(['Q2', '$120K', '$25K', '8%'])
139
tabular.add_hline()
140
```
141
142
### Extended Table Types
143
144
Advanced table environments for specific use cases and enhanced functionality.
145
146
```python { .api }
147
class Tabularx(Tabular):
148
def __init__(self, width, columns, *, width_argument=None, **kwargs):
149
"""
150
Extended tabular with automatic column width adjustment.
151
152
Parameters:
153
- width: str, total table width
154
- columns: str, column specification with 'X' columns
155
- width_argument: str, width specification format
156
157
Requires:
158
- tabularx package
159
"""
160
161
class LongTable(Tabular):
162
"""
163
Multi-page table environment.
164
165
Requires:
166
- longtable package
167
"""
168
169
class Tabu(Tabular):
170
"""
171
Enhanced tabular environment with advanced features.
172
173
Requires:
174
- longtabu package
175
"""
176
177
class LongTabu(Tabu):
178
"""
179
Multi-page tabu table.
180
181
Requires:
182
- longtabu package
183
"""
184
185
class LongTabularx(Tabular):
186
"""
187
Multi-page tabularx table.
188
189
Requires:
190
- ltxtable package
191
"""
192
```
193
194
Usage example:
195
196
```python
197
from pylatex import Document, NoEscape
198
from pylatex.table import Tabularx, LongTable
199
200
doc = Document()
201
202
# Automatic width adjustment
203
with doc.create(Tabularx(NoEscape(r'\textwidth'), 'X[l] X[c] X[r]')) as table:
204
table.add_row(['Left aligned', 'Centered', 'Right aligned'])
205
table.add_row(['This column adjusts', 'This too', 'And this'])
206
207
# Long table for multi-page content
208
with doc.create(LongTable('|l|p{4cm}|')) as longtable:
209
longtable.add_hline()
210
longtable.add_row(['Item', 'Description'])
211
longtable.add_hline()
212
longtable.end_table_header() # Repeat on each page
213
214
for i in range(100):
215
longtable.add_row([f'Item {i}', f'Description of item {i}'])
216
```
217
218
### Multi-Column and Multi-Row Cells
219
220
Classes for creating cells that span multiple columns or rows.
221
222
```python { .api }
223
class MultiColumn:
224
def __init__(self, size, align, content, *, color=None, data=None):
225
"""
226
Cell spanning multiple columns.
227
228
Parameters:
229
- size: int, number of columns to span
230
- align: str, alignment ('l', 'c', 'r')
231
- content: str or LatexObject, cell content
232
- color: str, background color
233
- data: additional cell data
234
"""
235
236
class MultiRow:
237
def __init__(self, size, width, content, *, color=None, data=None):
238
"""
239
Cell spanning multiple rows.
240
241
Parameters:
242
- size: int, number of rows to span
243
- width: str, cell width specification
244
- content: str or LatexObject, cell content
245
- color: str, background color
246
- data: additional cell data
247
248
Requires:
249
- multirow package
250
"""
251
252
class ColumnType:
253
def __init__(self, name, base_type, modifier):
254
"""
255
Custom column type definition.
256
257
Parameters:
258
- name: str, new column type name
259
- base_type: str, base column type to extend
260
- modifier: str, LaTeX code to modify the column
261
262
Requires:
263
- array package
264
"""
265
```
266
267
Usage example:
268
269
```python
270
from pylatex import Document, Tabular
271
from pylatex.table import MultiColumn, MultiRow
272
273
doc = Document()
274
275
with doc.create(Tabular('|c|c|c|c|')) as table:
276
table.add_hline()
277
278
# Multi-column header
279
table.add_row([MultiColumn(4, align='c', content='Annual Report')])
280
table.add_hline()
281
282
# Regular headers
283
table.add_row(['Quarter', 'Revenue', 'Expenses', 'Profit'])
284
table.add_hline()
285
286
# Multi-row cell
287
table.add_row([MultiRow(2, width='*', content='H1'),
288
'$100K', '$60K', '$40K'])
289
table.add_row(['', '$120K', '$70K', '$50K'])
290
table.add_hline()
291
292
table.add_row([MultiRow(2, width='*', content='H2'),
293
'$110K', '$65K', '$45K'])
294
table.add_row(['', '$130K', '$75K', '$55K'])
295
table.add_hline()
296
```
297
298
## Table Formatting Options
299
300
### Column Specifications
301
302
Common column specification patterns:
303
304
- **Basic alignment**: `'lrc'` (left, right, center)
305
- **Fixed width**: `'p{3cm}'` (paragraph column)
306
- **Vertical lines**: `'|l|c|r|'` (borders between columns)
307
- **Multiple lines**: `'||c||'` (double lines)
308
- **Mixed types**: `'l|p{2cm}|r'` (combination)
309
310
### Professional Styling
311
312
```python
313
from pylatex import Document, Package
314
from pylatex.table import Tabular
315
316
doc = Document()
317
doc.packages.append(Package('booktabs'))
318
doc.packages.append(Package('xcolor', options=['table']))
319
320
# Professional table styling
321
with doc.create(Tabular('lcc', booktabs=True)) as table:
322
table.add_row(['Item', 'Value', 'Change'], mapper=lambda x: Command('textbf', x))
323
table.add_hline()
324
table.add_row(['Revenue', '$1.2M', '+15%'])
325
table.add_row(['Profit', '$300K', '+22%'], color='lightgray')
326
table.add_row(['Growth', '18%', '+3%'])
327
```
328
329
### Color and Spacing
330
331
```python
332
from pylatex import Document, Command, NoEscape
333
from pylatex.table import Tabular
334
335
doc = Document()
336
337
# Custom spacing and colors
338
with doc.create(Tabular('lcc', row_height=1.5, col_space='10pt')) as table:
339
# Colored rows
340
table.add_row(['Header 1', 'Header 2', 'Header 3'], color='lightblue')
341
table.add_row(['Data 1', 'Data 2', 'Data 3'])
342
table.add_row(['Data 4', 'Data 5', 'Data 6'], color='lightgray')
343
344
# Colored lines
345
table.add_hline(color='red')
346
```
347
348
## Advanced Table Features
349
350
### Dynamic Table Generation
351
352
```python
353
from pylatex import Document, Section
354
from pylatex.table import Table, Tabular
355
356
def create_data_table(data, headers):
357
"""Create table from data structure."""
358
with doc.create(Table(position='htbp')) as table:
359
table.add_caption('Generated Data Table')
360
361
# Calculate column spec based on data
362
col_spec = 'l' + 'c' * (len(headers) - 1)
363
364
with table.create(Tabular(col_spec, booktabs=True)) as tabular:
365
# Add headers
366
tabular.add_row(headers)
367
tabular.add_hline()
368
369
# Add data rows
370
for row in data:
371
tabular.add_row(row)
372
373
# Usage
374
doc = Document()
375
headers = ['Name', 'Age', 'Department', 'Salary']
376
employee_data = [
377
['Alice Johnson', 28, 'Engineering', '$75,000'],
378
['Bob Smith', 34, 'Marketing', '$65,000'],
379
['Carol Davis', 29, 'Design', '$70,000']
380
]
381
382
create_data_table(employee_data, headers)
383
```
384
385
### Complex Table Layouts
386
387
```python
388
from pylatex import Document, Command, NoEscape
389
from pylatex.table import Tabular, MultiColumn, MultiRow
390
391
doc = Document()
392
393
# Complex business report table
394
with doc.create(Tabular('|l|c|c|c|c|')) as table:
395
table.add_hline()
396
397
# Title row
398
table.add_row([MultiColumn(5, align='c',
399
content=Command('textbf', 'Financial Summary'))])
400
table.add_hline()
401
402
# Period headers
403
table.add_row(['', MultiColumn(2, align='c', content='2023'),
404
MultiColumn(2, align='c', content='2024')])
405
table.add_hline()
406
407
# Quarter headers
408
table.add_row(['Metric', 'Q3', 'Q4', 'Q1', 'Q2'])
409
table.add_hline()
410
411
# Data with multi-row categories
412
table.add_row([MultiRow(2, width='*', content='Revenue'),
413
'$1.2M', '$1.5M', '$1.8M', '$2.1M'])
414
table.add_row(['', '(+8%)', '(+25%)', '(+20%)', '(+17%)'])
415
table.add_hline()
416
417
table.add_row([MultiRow(2, width='*', content='Profit'),
418
'$240K', '$350K', '$450K', '$580K'])
419
table.add_row(['', '(+12%)', '(+46%)', '(+29%)', '(+29%)'])
420
table.add_hline()
421
```
422
423
## Error Handling
424
425
```python { .api }
426
class TableError(Exception):
427
"""Base class for table-related errors."""
428
429
class TableRowSizeError(TableError):
430
"""Raised when row size doesn't match table specification."""
431
```
432
433
Tables automatically validate row sizes against column specifications and provide helpful error messages when mismatches occur.
434
435
## Package Dependencies
436
437
Different table types require specific LaTeX packages:
438
439
- **Basic tables**: No additional packages required
440
- **Tabularx**: `tabularx` package
441
- **LongTable**: `longtable` package
442
- **Tabu/LongTabu**: `longtabu` package
443
- **MultiRow**: `multirow` package
444
- **Booktabs**: `booktabs` package
445
- **Colors**: `xcolor` package with `table` option
446
447
PyLaTeX automatically manages these dependencies when you use the corresponding classes.