N
N
NyxDeveloper2021-02-10 12:28:12
Django
NyxDeveloper, 2021-02-10 12:28:12

How to generate html table in view and export it to excel?

I want to implement functionality in my application that is able to export an html table to an xls file. pandas.read_html() has this functionality, but I don’t know how to pass a table to it, because it is generated by the django template engine. In general, you need to feed this tablet to the pandas. Tell me how you can do this, I found little documentation on my question, so it's possible that I complicated everything a lot. Who faced similar, I ask to give the link to docks or to show an example of similar export. Thank you!

UPD:
In short, I found a way to implement this beautifully, but for some reason it does not work to the end. I decided to use the jinja2 module, with which I generate a file with a real-time table.

def prj_rep_export(request):
    with open(os.path.join(BASE_DIR, 'table.html'), 'r') as file:
        #    list - queryset, по которому в шаблоне проходит цикл чтобы вывести строки таблицы
        #    большепеременных в шаблоне нет
        table = pd.read_html(Template(file.read()).render(list=get_project_list(request.user)))
    table.to_excel("data.xlsx")
    return FileResponse(open('data.xlsx'), 'rb'), as_attachment=True)


The problem is that calling Template(file.read()).render(list=get_project_list(request.user)) returns an empty string.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NyxDeveloper, 2021-02-10
@NyxDeveloper

The first thing I want to say - NEVER DO THIS!
In general, it is easier to give this matter to pandas, he will figure it out himself. And no html without a link in the form of a url!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question