最近在做前端界面時遇到一個需求,要在前端界面實現數據庫數據的excel導出,經過多方查閱資料終於找到解決方法!
下面貼出導出excel函數的代碼片段。
# -*- coding: utf-8 -*-
import MySQLdb
import xlwt
import StringIO
from django.shortcuts import HttpResponse
from MySQLdb.cursors import DictCursor
conn = MySQLdb.connect(host='192.168.2.4', user='root', passwd='zj88friend', db='zz91crm', port=3306, charset='utf8', cursorclass = MySQLdb.cursors.DictCursor)#其中cursorclass設定返回數據類型為字典
cur = conn.cursor()#獲取游標
def export_xls(request):
sql='select id,label from category'
conn.cursor().execute(sql)#執行sql語句
conn.cursor().fetchall()#獲取查詢結果
response = HttpResponse(content_type='application/vnd.ms-excel')#指定返回為excel文件
response['Content-Disposition'] = 'attachment;filename=export_agencycustomer.xls'#指定返回文件名
wb = xlwt.Workbook(encoding = 'utf-8')#設定編碼類型為utf8
sheet = wb.add_sheet(u'類別')#excel里添加類別
sheet.write(0,0, 'id')
sheet.write(0,1, '名字')
row = 1
for list in result:
sheet.write(row,0, list['id'])
sheet.write(row,1, list['label'])
row=row + 1
output = StringIO.StringIO()
wb.save(output)
output.seek(0)
response.write(output.getvalue())
return response