Practice extracting Pandas DataFrames from dictionaries, CSVs, Excel sheets, SQLite databases, and MySQL connections to render formatted Platypus tables directly inside Google Colab.
View on GitHub
Our main script table_pandas.py reads records as a list (my_data) from a data provider module and builds a ReportLab Platypus table.
Inside table_pandas.py, we import my_data:
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table, TableStyle, colors
from table_pandas_data import my_data # import the data list
my_doc = SimpleDocTemplate('output/dataframe_table.pdf', pagesize=letter)
c_width = [1.5 * inch, 1.0 * inch, 1.2 * inch, 1.2 * inch]
t = Table(my_data, colWidths=c_width, repeatRows=1)
t.setStyle(TableStyle([
('FONTSIZE', (0, 0), (-1, -1), 12),
('BACKGROUND', (0, 0), (-1, 0), colors.lightgreen),
('VALIGN', (0, 0), (-1, 0), 'TOP'),
('GRID', (0, 0), (-1, -1), 0.5, colors.grey)
]))
elements = [t]
my_doc.build(elements)
Inside table_pandas_data.py, we construct a Pandas DataFrame from a Python dictionary and convert it into a list using df.values.tolist():
import pandas as pd
my_dict = {
'NAME': ['Ravi', 'Raju', 'Alex', 'Ron', 'King', 'Jack'],
'ID': [1, 2, 3, 4, 5, 6],
'MATH': [80, 40, 70, 70, 60, 30],
'ENGLISH': [80, 70, 40, 50, 60, 30]
}
df = pd.DataFrame(data=my_dict)
my_data = df.values.tolist()
my_data.insert(0, list(df.columns)) # include column headers
Pandas can query SQLite database tables directly using SQLAlchemy engines. We wrap database operations inside try-except blocks to handle SQL connectivity errors gracefully:
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
db_file = 'my_db.db'
file1 = 'sqlite:///' + db_file
my_conn = create_engine(file1)
try:
df = pd.read_sql("SELECT * FROM student", my_conn)
my_data = df.values.tolist()
my_data.insert(0, list(df.columns))
except SQLAlchemyError as e:
error = str(e.__dict__['orig'])
print(error)
To pull records from a MySQL database table, simply swap out the SQLAlchemy connection string format:
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://<userid>:<password>@localhost/<database_name>")
from pathlib import Path
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table, TableStyle, colors
from table_pandas_data import my_data
output_dir = Path('output')
output_dir.mkdir(exist_ok=True)
my_path = output_dir / 'dataframe_table.pdf'
my_doc = SimpleDocTemplate(str(my_path), pagesize=letter)
c_width = [1.5 * inch, 1.0 * inch, 1.2 * inch, 1.2 * inch]
t = Table(my_data, colWidths=c_width, repeatRows=1)
t.setStyle(TableStyle([
('FONTSIZE', (0, 0), (-1, -1), 12),
('BACKGROUND', (0, 0), (-1, 0), colors.lightgreen),
('VALIGN', (0, 0), (-1, 0), 'TOP'),
('GRID', (0, 0), (-1, -1), 0.5, colors.grey)
]))
elements = [t]
my_doc.build(elements)
print(f"PDF DataFrame table generated successfully: {my_path}")
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
db_file = 'my_db.db'
file1 = 'sqlite:///' + db_file
my_conn = create_engine(file1)
try:
df = pd.read_sql("SELECT * FROM student", my_conn)
my_data = df.values.tolist()
my_data.insert(0, list(df.columns))
except SQLAlchemyError as e:
# Fallback dictionary source if database file is absent
my_dict = {
'NAME': ['Ravi', 'Raju', 'Alex', 'Ron', 'King', 'Jack'],
'ID': [1, 2, 3, 4, 5, 6],
'MATH': [80, 40, 70, 70, 60, 30],
'ENGLISH': [80, 70, 40, 50, 60, 30]
}
df = pd.DataFrame(data=my_dict)
my_data = df.values.tolist()
my_data.insert(0, list(df.columns))
Q: Can I style alternating rows in a Pandas DataFrame PDF table?
A: Yes, you can apply background color styles dynamically using list comprehensions or `TableStyle` commands such as `('BACKGROUND', (0, i), (-1, i), colors.beige)` inside a loop.
Q: How do I handle large database tables that span multiple pages?
A: Set `repeatRows=1` in the `Table` constructor so that header rows automatically repeat at the top of each new page.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.