This is the test code I use to connect to the database, get some data and write it to a table:
# -*- coding: utf-8 -*-
import psycopg2
import pylatex as pl
try:
conn = psycopg2.connect("dbname='xxxxx' user='xxxxx'
host='xxxxx.com' password='xxxx'")
print "Estoy dentro de la base de datos"
cur = conn.cursor()
cur.execute("""SELECT fechor,pedido, estado
FROM client.ordenes_de_venta_completo
LIMIT 10""")
rows = cur.fetchall()
df = pd.DataFrame(rows)
doc = Document('basic')
header = [desc[0] for desc in cur.description]
with doc.create(pl.Section('Ultimos 10 productos')):
with doc.create(pl.Tabular('ccc')) as table:
table.add_hline()
table.add_row(header[0], header[1], header[2])
table.add_hline()
for row in df.index:
table.add_row(list(df.loc[row,:]))
table.add_hline()
doc.generate_pdf(clean_tex=False)
except:
print "No puedo conectar a la base de datos"
The problem is when creating the table header. I would like to replace this line:
table.add_row(header[0], header[1], header[2])
by:
table.add_row(column_name for column_name in header)
since when the PostgreSQL query varies, the number of fields must not necessarily be 3 and the table can therefore have a different number of columns.
The problem is that doing this produces the following error:
TableRowSizeError: Number of cells added to table (0) did not match table width (3)
When you do
table.add_row(column_name for column_name in header)
this you are passing a generator to the function as the only argument. You can pass the list directly:Or in any case unpack it with
*
, which is equivalent to passing each of its elements as individual arguments to the function:Since you must specify the structure of the table (and the number of columns) in the constructor of
pylatex.Tabular
, you must create the argumenttable_spec
dynamically. If you only want centered columns you can simply do: