我必须编写一个函数,该函数在输入时具有表名和该查询的条件/过滤器,在输出时返回一个应由客户端(浏览器)自动下载的链接。

如何使用python / django实现此任务?

例如。我已经写了一小段代码,但是我不确定它是否正确运行,并且没有查询条件解析的实现(我不知道如何实现):

direct_db.py:

from django.db import connection

class DirectSQL:
    def __init__(self,in_sql):
        self.sql=in_sql
        self.cursor = connection.cursor()
        self.cursor.execute(in_sql)
    def getDescription(self):
        columns = [desc[0] for desc in self.cursor.description]
        return columns
    def getResult(self):
        row = self.cursor.fetchall()
        return row
    def getResultAsDict(self):
        desc = self.cursor.description
        return [dict(zip([col[0].lower() for col in desc], row)) for row in self.cursor.fetchall()]


excel.py:

from ecc.direct_db import DirectSQL
import pandas as ps

class Excel:
    def __init__(self, table_name):
        self.table_name = table_name
    def convert(in_args):
        q = DirectSQL("select * from self.table_name" ) # where... order by... like...
        columns = [desc[0] for desc in q.getDescription()]
        data = q.getResults()
        df = ps.DataFrame(list(data), columns)
        writer = ps.ExcelWriter('converted.xlsx')
        df.to_excel(writer, sheet_name='converted')
        writer.save()

最佳答案

之前,我已经使用过类似的方法,我使用了xlsxwriter,您可以检查其docs以了解如何创建xlsx以及如何将数据设置到其中。然后,您需要一些视图:

from django.views.generic import View
from django.http import HttpResponse


class CreateReport(View):

    def get_data(self):
        # Query your data here, probably using self.request to get query string
        ...
        return data

    def generate_report(self):
        # Here you will create xlsx doc and populate with data according to docs linked before
        ...
        return workbook

    def get(self, request, *args, **kwargs):
        document = self.generate_report()
        _file = open(document.filename, 'r')

        response(HttpResponse(_file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
        response['Content-Disposition'] = 'attachment; filename=%s' % document.filename.split('/')[-1]  # Here will return a full path, that's why probably you will need a split to get only the filename
        add_never_cache_headers(response=response)  # To avoid download the same file with out of date data.
        return response


然后,您将需要一个url

from myapp.views import CreateReport
url(r'^create_report/(?P<some_param_if_needed>[-\w]+)',
                       CreateReport.as_view(),
                       name='create_report'),


最后在模板中

<a href="{% url 'create_report' report_name %}">Download Report</a>


编辑

这是get_data()方法的更完整示例。

get_data(self):
    # Let's supose you have a `MyElements` model
    elements = MyElements.objects.all()

    # And let's supose you want to filter data with some GET parameter
    filter = self.request.GET.get('filter_name', None)

    if filter is not None:
        elements = elements.filter(filter_field=filter)

    return elements

关于python - 使用Django下载xlsx格式的SQL数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30668053/

10-12 12:51
查看更多