Search code examples
pythonpandaspdfreportlab

Adding dateframe to PDF using Reportlab python


I am trying to display my date frame in a pdf using Lab Report. I have figured out so far what I want but I do not know how to add the index so this is missing. My pdf looks like this: My data frame:

            00-04  04-08  08-12  12-16  16-20  20-24
2017-12-09  17671  16443  14300  15317  16398  16398
2017-12-10  16632  17611  16486  10562  10562  13014
2017-12-11  11355      0      0      0   8569  11697

My code:

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import *
from reportlab.lib import colors
import pandas as pd
import random

PATH_OUT = "C:\\"

elements = []
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("Analysis_Lists.pdf", pagesize=A3, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
elements.append(Paragraph("Wind Park Available Flex Neg", styles['Title']))

data = [[random.random() for i in range(1,4)] for j in range (1,8)]
df = resultado(lista,df_output,labels)
lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()

ts = [('ALIGN', (1,1), (-1,-1), 'CENTER'),
     ('LINEABOVE', (0,0), (-1,0), 1, colors.black),
     ('LINEBELOW', (0,0), (-1,0), 1, colors.black),
     ('FONT', (0,0), (-1,0), 'Times-Bold'),
     ('LINEBELOW', (0,-1), (-1,-1), 1, colors.black),
     ('BACKGROUND',(1,1),(-2,-2),colors.white),
     ('TEXTCOLOR',(0,0),(1,-1),colors.black)]

table = Table(lista, style=ts)
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
Explanation = [["The lost HT flex in the last week for 50 Hz SRL is ."],
["The lost HT flex in the last week for Tennet SRL is "],
["The lost HT flex in the last week for Amprion SRL is "],
]

data2 = [[Paragraph(cell, s) for cell in row] for row in Explanation]
e=Table(data2,spaceAfter=20)

elements.append(table)
elements.append(e)

I have added columns and values but not sure how to add an index and my index is DateTime stamp:

l = df.index[:,].strftime('%Y/%m/%d')
l = l.tolist()
l = [u'2017/12/09', u'2017/12/10', u'2017/12/11']

Can someone give me a hint how to continue with this process? I am not familiar with reportlab. Any help or suggestion would be great I have read Report Lab user guide


Solution

  • As mentioned in the comments, I think the PDF problem is a "Red-Herring". I think the true issue is just getting your index into the columns.

    df_2 = df.reset_index().rename(columns = {'index':'date'}) 
    #.rename is just renaming 'index' into 'date'. you can put anything you want in there
    

    and now pass df2 into lista instead of df.

    The rest of the code will work as expected.