python和Django导出mssql查询到excel

时间:2018-04-16 00:36:27

标签: python sql-server django sqlalchemy django-views

我在django中构建了一个应用程序,用于从mssql服务器中提取数据,并在模板上的表格中显示结果。

我现在要做的是将相同的sql查询结果导出到excel文件。我已经使用pymssql驱动程序连接到db和pysqlalchemy。

3 个答案:

答案 0 :(得分:0)

这就是我所做的,但有些人在调用函数时没有创建excel文件

def download_excel(request):
    if "selectdate" in request.POST:
        if "selectaccount" in request.POST:
            selected_date = request.POST["selectdate"]
            selected_acc = request.POST["selectaccount"]
        if selected_date==selected_date:
            if selected_acc==selected_acc:
                convert=datetime.datetime.strptime(selected_date, "%Y-%m-%d").toordinal()
                engine=create_engine('mssql+pymssql://username:password@servername /db')
                connection = engine.connect()
                metadata=MetaData()
                fund=Table('gltrxdet',metadata,autoload=True,autoload_with=engine)
                rate=Table('gltrx_all',metadata,autoload=True,autoload_with=engine)
                stmt=select([fund.columns.account_code,fund.columns.description,fund.columns.nat_balance,fund.columns.rate_type_home,rate.columns.date_applied,rate.columns.date_entered,fund.columns.journal_ctrl_num,rate.columns.journal_ctrl_num])
                stmt=stmt.where(and_(rate.columns.journal_ctrl_num==fund.columns.journal_ctrl_num,fund.columns.account_code==selected_acc,rate.columns.date_entered==convert))

                df = pd.read_sql(stmt,connection)

                writer = pd.ExcelWriter('C:\excel\export.xls')
                df.to_excel(writer, sheet_name ='bar')
                writer.save()

答案 1 :(得分:0)

我的代码确实有效。我以为它会将excel文件保存到C:\ excel'文件夹所以我在文件夹中寻找文件,但我找不到excel文件。 excel文件实际上已导出到我的django项目文件夹中。

如何让最终用户能够将文件下载到桌面而不是将其导出到服务器本身

答案 2 :(得分:0)

我设法让它花费大量时间进行研究。此代码将sql查询导出到excel文件,这将允许最终用户下载excel文件

import pandas as pd
from django.http import HttpResponse
try:
    from io import BytesIO as IO # for modern python
except ImportError:
    from StringIO import StringIO as IO # for legacy python

def download_excel(request):
    if "selectdate" in request.POST:
        if "selectaccount" in request.POST:
            selected_date = request.POST["selectdate"]
            selected_acc = request.POST["selectaccount"]
        if selected_date==selected_date:
            if selected_acc==selected_acc:
                convert=datetime.datetime.strptime(selected_date, "%Y-%m-%d").toordinal()
                engine=create_engine('mssql+pymssql://username:password@servername /db')

               
                metadata=MetaData(connection)
                fund=Table('gltrxdet',metadata,autoload=True,autoload_with=engine)
                rate=Table('gltrx_all',metadata,autoload=True,autoload_with=engine)
                      stmt=select([fund.columns.account_code,fund.columns.description,fund.columns.nat_balance,rate.columns.date_applied,fund.columns.journal_ctrl_num,rate.columns.journal_ctrl_num])
                stmt=stmt.where(and_(rate.columns.journal_ctrl_num==fund.columns.journal_ctrl_num,fund.columns.account_code==selected_acc,rate.columns.date_applied==convert))
                results=connection.execute(stmt)
                
		sio = StringIO()
                df = pd.DataFrame(data=list(results), columns=results.keys())

                ####dowload excel file##########
                excel_file = IO()
                xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')
                df.to_excel(xlwriter, 'sheetname')
                xlwriter.save()
                xlwriter.close()
                excel_file.seek(0)

                response = HttpResponse(excel_file.read(), content_type='application/ms-excel vnd.openxmlformats-officedocument.spreadsheetml.sheet')
                # set the file name in the Content-Disposition header
                response['Content-Disposition'] = 'attachment; filename=myfile.xls'
                return response