python - 使用 Django 下载 xlsx 格式的 SQL 数据

标签 python django excel pandas

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

如何使用 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 以及如何将数据设置到其中。那么你应该需要一些 View :

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/

相关文章:

javascript - 如何让spawnSync和fs.readFile先后执行?

python - 确定线程何时等待锁释放

Django 聚合 - 零值除法

python - 我如何使用 Django objects.filter 执行此操作?

Django South 迁移错误 "contains null values"字段为 null=True

python - 使用点分隔字符串的动态字典值访问

python - PyCharm Nosetests - 无法识别的测试

excel - 逐行读取csv流,为Excel Range创建数组

excel - 需要Excel表格公式

excel - 如何使用 vba 代码关闭 Visual Basic 应用程序