GreenCoder90
GreenCoder90

Reputation: 363

ReportLab Table Layout

How can I edit this code so that It has 7 columns and 5 rows with the columns names appearing at the top?

# PDF document layout
table_style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'),
                       ('TEXTCOLOR',(1,1),(-2,-2),colors.red),
                       ('VALIGN',(0,0),(0,-1),'TOP'),
                       ('TEXTCOLOR',(0,0),(0,-1),colors.blue),
                       ('ALIGN',(0,-1),(-1,-1),'CENTER'),
                       ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
                       ('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ])

Upvotes: 2

Views: 1485

Answers (1)

Adam Moller
Adam Moller

Reputation: 973

The shape of the data is what defines the shape of the table in ReportLab. Table data can be stored in a list of lists. Each list in the list is a row (Tuples may also work). Here is an example:

data = [['00', '01', '02', '03', '04'], # First row or headers
        ['10', '11', '12', '13', '14'], # Second row
        ['20', '21', '22', '23', '24'], # Third row
        ['30', '31', '32', '33', '34'],] # Fourth row

More information is available on page 84 of the documentation available here: https://www.reportlab.com/docs/reportlab-userguide.pdf

In your example, you are showing how to define the style or appearance of the table. The 2-Tuples at index [1] and [2] define the range of cells for which the formatting should apply. The first 2-Tuple is (Start Column, Start Row) and the second 2-Tuple is (End Column, End Row). You can think of this as if you were selecting a range of cells on a spreadsheet with your mouse, starting at the first cell and stopping at the second cell. Negative indexes can also be used in the same way they are used for lists in Python.

The following example is a table of 7 columns and any number of rows. The first row is the header.

all_cells = [(0, 0), (-1, -1)] 
header = [(0, 0), (-1, 0)]
column0 = [(0, 0), (0, -1)]
column1 = [(1, 0), (1, -1)]
column2 = [(2, 0), (2, -1)]
column3 = [(3, 0), (3, -1)]
column4 = [(4, 0), (4, -1)]
column5 = [(5, 0), (5, -1)]
column6 = [(6, 0), (6, -1)]
table_style = TableStyle([
    ('VALIGN', all_cells[0], all_cells[1], 'TOP'),
    ('LINEBELOW', header[0], header[1], 1, colors.black),
    ('ALIGN', column0[0], column0[1], 'LEFT'),
    ('ALIGN', column1[0], column1[1], 'LEFT'),
    ('ALIGN', column2[0], column2[1], 'LEFT'),
    ('ALIGN', column3[0], column3[1], 'RIGHT'),
    ('ALIGN', column4[0], column4[1], 'RIGHT'),
    ('ALIGN', column5[0], column5[1], 'LEFT'),
    ('ALIGN', column6[0], column6[1], 'RIGHT'),
])

Upvotes: 1

Related Questions