0
# Tables
1
2
Flexible table creation from flat lists or 2D arrays with customizable alignment, supporting various data input formats and styling options. MDUtils provides comprehensive table creation capabilities with automatic formatting, alignment controls, and positioning options.
3
4
## Capabilities
5
6
### Basic Table Creation
7
8
Create tables from flat lists with specified dimensions and alignment options.
9
10
```python { .api }
11
class MdUtils:
12
def new_table(self, columns: int, rows: int, text: List[str], text_align: Optional[Union[str, list]] = "center", marker: str = "") -> str:
13
"""
14
Create a table from a flat list of strings.
15
16
Parameters:
17
- columns (int): Number of columns in the table
18
- rows (int): Number of rows in the table
19
- text (List[str]): Flat list of cell contents (columns Γ rows elements)
20
- text_align (str or list, optional): Alignment ('left', 'center', 'right') for all columns or per-column list
21
- marker (str, optional): Marker for positioning table at specific location
22
23
Returns:
24
str: Formatted markdown table
25
"""
26
```
27
28
**Usage Example:**
29
30
```python
31
from mdutils import MdUtils
32
33
md = MdUtils(file_name='basic_table_example')
34
35
# Simple 2x3 table (2 columns, 3 rows)
36
table_data = [
37
'Name', 'Age', # Header row
38
'Alice', '25', # Row 1
39
'Bob', '30' # Row 2
40
]
41
md.new_table(columns=2, rows=3, text=table_data)
42
43
# Table with custom alignment
44
product_data = [
45
'Product', 'Price', 'Stock', # Headers
46
'Laptop', '$999', '15', # Row 1
47
'Mouse', '$25', '50', # Row 2
48
'Keyboard', '$75', '30' # Row 3
49
]
50
md.new_table(columns=3, rows=4, text=product_data, text_align='left')
51
52
# Table with per-column alignment
53
mixed_align_data = [
54
'Item', 'Quantity', 'Total',
55
'Books', '10', '$150.00',
56
'Pens', '25', '$12.50'
57
]
58
# Left align first column, center second, right align third
59
alignments = ['left', 'center', 'right']
60
md.new_table(columns=3, rows=3, text=mixed_align_data, text_align=alignments)
61
```
62
63
### Array-Based Table Creation
64
65
Create tables from 2D arrays for more intuitive data structure handling.
66
67
```python { .api }
68
class MdUtils:
69
def new_table_array(self, data: List[List[str]], text_align: Optional[Union[str, list]] = None, marker: str = "") -> str:
70
"""
71
Create a table from a 2D array structure.
72
73
Parameters:
74
- data (List[List[str]]): 2D array where each inner list represents a table row
75
- text_align (str or list, optional): Alignment specification
76
- marker (str, optional): Marker for positioning table at specific location
77
78
Returns:
79
str: Formatted markdown table
80
"""
81
```
82
83
**Usage Example:**
84
85
```python
86
from mdutils import MdUtils
87
88
md = MdUtils(file_name='array_table_example')
89
90
# 2D array approach - more intuitive
91
table_data = [
92
['Language', 'Year', 'Creator'], # Header row
93
['Python', '1991', 'Guido van Rossum'], # Row 1
94
['JavaScript', '1995', 'Brendan Eich'], # Row 2
95
['Go', '2009', 'Google'] # Row 3
96
]
97
md.new_table_array(data=table_data, text_align='center')
98
99
# Financial data table with right alignment for numbers
100
financial_data = [
101
['Quarter', 'Revenue', 'Profit', 'Growth'],
102
['Q1 2023', '$1,200,000', '$150,000', '12%'],
103
['Q2 2023', '$1,350,000', '$180,000', '15%'],
104
['Q3 2023', '$1,500,000', '$225,000', '18%']
105
]
106
# Left align quarter, right align numbers
107
alignments = ['left', 'right', 'right', 'right']
108
md.new_table_array(data=financial_data, text_align=alignments)
109
```
110
111
### Table Tool Classes
112
113
Direct access to table creation tools for advanced table manipulation and custom formatting.
114
115
```python { .api }
116
class Table:
117
def __init__(self):
118
"""Initialize a table creation tool."""
119
120
def create_table(self, columns: int, rows: int, text: List[str], text_align: Optional[Union[str, list]] = None) -> str:
121
"""
122
Create table from flat list with specified dimensions.
123
124
Parameters:
125
- columns (int): Number of columns
126
- rows (int): Number of rows
127
- text (List[str]): Flat list of cell contents
128
- text_align (str or list, optional): Alignment specification
129
130
Returns:
131
str: Formatted markdown table
132
"""
133
134
def create_table_array(self, data: List[List[str]], text_align: Optional[Union[str, list]] = None) -> str:
135
"""
136
Create table from 2D array structure.
137
138
Parameters:
139
- data (List[List[str]]): 2D array of table data
140
- text_align (str or list, optional): Alignment specification
141
142
Returns:
143
str: Formatted markdown table
144
"""
145
146
@staticmethod
147
def _align(columns: int, text_align: Optional[Union[str, Iterable]] = None) -> str:
148
"""
149
Generate alignment row for markdown table.
150
151
Parameters:
152
- columns (int): Number of columns
153
- text_align (str or iterable, optional): Alignment specification
154
155
Returns:
156
str: Markdown table alignment row
157
"""
158
159
# Properties
160
rows: int # Number of rows in the table
161
columns: int # Number of columns in the table
162
```
163
164
**Usage Example:**
165
166
```python
167
from mdutils import MdUtils
168
from mdutils.tools import Table
169
170
md = MdUtils(file_name='table_tools_example')
171
172
# Using Table class directly
173
table_tool = Table()
174
175
# Create table using tool methods
176
data = ['Header 1', 'Header 2', 'Value 1', 'Value 2']
177
table_content = table_tool.create_table(columns=2, rows=2, text=data, text_align='center')
178
md.write(table_content)
179
180
# Create table from array
181
array_data = [
182
['Feature', 'Status'],
183
['Authentication', 'Complete'],
184
['Database', 'In Progress'],
185
['UI', 'Planning']
186
]
187
array_table = table_tool.create_table_array(data=array_data, text_align=['left', 'center'])
188
md.write(array_table)
189
190
# Access table properties
191
print(f"Table has {table_tool.rows} rows and {table_tool.columns} columns")
192
```
193
194
### Advanced Table Positioning
195
196
Use markers to position tables at specific locations within the document.
197
198
**Usage Example:**
199
200
```python
201
from mdutils import MdUtils
202
203
md = MdUtils(file_name='positioned_tables')
204
205
# Create content structure
206
md.new_header(level=1, title='Data Analysis Report')
207
md.new_paragraph('This report contains several data tables.')
208
209
# Create marker for first table
210
md.new_header(level=2, title='Sales Data')
211
md.new_paragraph('The following table shows our sales performance:')
212
sales_marker = md.create_marker('sales_table')
213
214
md.new_header(level=2, title='User Statistics')
215
md.new_paragraph('User engagement metrics are shown below:')
216
users_marker = md.create_marker('users_table')
217
218
# Create tables and place them at markers
219
sales_data = [
220
'Month', 'Sales', 'Target',
221
'January', '$45,000', '$40,000',
222
'February', '$52,000', '$45,000',
223
'March', '$48,000', '$50,000'
224
]
225
md.new_table(columns=3, rows=4, text=sales_data,
226
text_align=['left', 'right', 'right'],
227
marker=sales_marker)
228
229
users_data = [
230
['Metric', 'Value', 'Change'],
231
['Active Users', '12,500', '+5%'],
232
['New Signups', '850', '+12%'],
233
['Retention', '78%', '+2%']
234
]
235
md.new_table_array(data=users_data,
236
text_align=['left', 'center', 'right'],
237
marker=users_marker)
238
```
239
240
### Table Alignment Options
241
242
Comprehensive guide to table alignment specifications and their effects.
243
244
**Alignment Values:**
245
- `'left'` - Left-align column content
246
- `'center'` - Center-align column content
247
- `'right'` - Right-align column content
248
249
**Alignment Specification Methods:**
250
1. **Single string**: Same alignment for all columns
251
2. **List of strings**: Individual alignment per column
252
3. **None/default**: Center alignment for all columns
253
254
**Usage Example:**
255
256
```python
257
from mdutils import MdUtils
258
259
md = MdUtils(file_name='alignment_examples')
260
261
# Same alignment for all columns
262
md.new_header(level=2, title='Left Aligned Table')
263
left_data = ['Name', 'City', 'Country', 'John', 'New York', 'USA', 'Jane', 'London', 'UK']
264
md.new_table(columns=3, rows=3, text=left_data, text_align='left')
265
266
# Individual column alignments
267
md.new_header(level=2, title='Mixed Alignment Table')
268
mixed_data = [
269
['Product', 'Price', 'Rating', 'Notes'],
270
['Laptop', '$999.99', '4.5/5', 'Excellent performance'],
271
['Mouse', '$29.99', '4.2/5', 'Good ergonomics'],
272
['Monitor', '$299.99', '4.8/5', 'Great display quality']
273
]
274
# Left, right, center, left alignment
275
mixed_alignments = ['left', 'right', 'center', 'left']
276
md.new_table_array(data=mixed_data, text_align=mixed_alignments)
277
278
# Default center alignment (no text_align specified)
279
md.new_header(level=2, title='Default Center Aligned')
280
center_data = ['Feature', 'Available', 'SSL', 'Yes', 'Database', 'PostgreSQL']
281
md.new_table(columns=2, rows=3, text=center_data)
282
```
283
284
### Complex Table Examples
285
286
Real-world examples demonstrating advanced table creation patterns and data presentation.
287
288
**Usage Example:**
289
290
```python
291
from mdutils import MdUtils
292
293
md = MdUtils(file_name='complex_tables')
294
295
# Project status table with varied content
296
md.new_header(level=1, title='Project Dashboard')
297
298
project_status = [
299
['Project', 'Lead', 'Progress', 'Due Date', 'Status'],
300
['Website Redesign', 'Alice Johnson', '85%', '2023-12-15', 'π’ On Track'],
301
['Mobile App', 'Bob Smith', '60%', '2024-01-30', 'π‘ At Risk'],
302
['API Integration', 'Carol Davis', '95%', '2023-11-20', 'π’ On Track'],
303
['Database Migration', 'David Wilson', '30%', '2024-02-15', 'π΄ Behind']
304
]
305
alignments = ['left', 'left', 'center', 'center', 'center']
306
md.new_table_array(data=project_status, text_align=alignments)
307
308
# Financial summary with calculations
309
md.new_header(level=2, title='Quarterly Financial Summary')
310
financial_summary = [
311
'Category', 'Q1', 'Q2', 'Q3', 'Total',
312
'Revenue', '$125,000', '$138,000', '$142,000', '$405,000',
313
'Expenses', '$95,000', '$102,000', '$108,000', '$305,000',
314
'Profit', '$30,000', '$36,000', '$34,000', '$100,000',
315
'Margin', '24%', '26%', '24%', '25%'
316
]
317
financial_alignments = ['left', 'right', 'right', 'right', 'right']
318
md.new_table(columns=5, rows=5, text=financial_summary, text_align=financial_alignments)
319
320
# Technical specifications table
321
md.new_header(level=2, title='System Requirements')
322
tech_specs = [
323
['Component', 'Minimum', 'Recommended'],
324
['CPU', 'Intel i3 / AMD Ryzen 3', 'Intel i7 / AMD Ryzen 7'],
325
['RAM', '8 GB', '16 GB'],
326
['Storage', '256 GB SSD', '512 GB SSD'],
327
['GPU', 'Integrated', 'Dedicated 4GB+'],
328
['OS', 'Windows 10 / macOS 10.15', 'Windows 11 / macOS 12+']
329
]
330
tech_alignments = ['left', 'center', 'center']
331
md.new_table_array(data=tech_specs, text_align=tech_alignments)
332
```