Skip to content

Rendering spreadsheets as PDF tables

All the details on tables and options to style them are detailed on the dedicated page: Tables.

From a .csv spreadsheet

Example input file: color_srgb.csv

#!/usr/bin/env python3
# USAGE: ./csv2table.py color_srgb.csv
import csv, sys
from fpdf import FPDF, FontFace
from fpdf.drawing import color_from_hex_string

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=22)
with pdf.table() as table:
    with open(sys.argv[1], encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file, delimiter=",")
        for i, row in enumerate(reader):
            style = None
            if i > 0:
                # We color the row based on the hexadecimal code in the 2nd column:
                style = FontFace(fill_color=color_from_hex_string(row[1]))
            table.row(row, style=style)
pdf.output("from-csv.pdf")

From a .xlsx spreadsheet

Example input file: color_srgb.xlsx

#!/usr/bin/env python3
# Script Dependencies:
#    openxlsx
# USAGE: ./xlsx2table.py color_srgb.xlsx
import sys
from fpdf import FPDF, FontFace
from fpdf.drawing import color_from_hex_string
from openpyxl import load_workbook

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=22)
wb = load_workbook(sys.argv[1])
ws = wb.active
with pdf.table() as table:
    for i, row in enumerate(ws.rows):
        style = None
        if i > 0:
            # We color the row based on the hexadecimal code in the 2nd column:
            style = FontFace(fill_color=color_from_hex_string(row[1]))
        table.row([cell.value for cell in row], style=style)
pdf.output("from-xlsx.pdf")

From an .ods spreadsheet

Example input file: color_srgb.ods

#!/usr/bin/env python3
# Script Dependencies:
#    odfpy
# USAGE: ./ods2table.py color_srgb.ods
import sys
from fpdf import FPDF, FontFace
from fpdf.drawing import color_from_hex_string
from odf.opendocument import load
from odf.table import Table, TableCell, TableRow

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=22)
ods = load(sys.argv[1])
for sheet in ods.getElementsByType(Table):
    with pdf.table() as table:
        for i, row in enumerate(sheet.getElementsByType(TableRow)):
            row = [str(cell) for cell in row.getElementsByType(TableCell)]
            style = None
            if i > 0:
                # We color the row based on the hexadecimal code in the 2nd column:
                style = FontFace(fill_color=color_from_hex_string(row[1]))
            table.row(row, style=style)
pdf.output("from-ods.pdf")

From pandas DataFrame

cf. Maths documentation page