后台代码,在url.py自行定义接口,浏览器访问即可下载
import MySQLdb import xlwt from io import BytesIO from django.shortcuts import HttpResponse from MySQLdb.cursors import DictCursor def export_xls_out(request): conn = MySQLdb.connect(host='',user='',passwd='',db='',port=3306,charset='utf8',cursorclass=MySQLdb.cursors.DictCursor) #数据库参数自己配置 sql='select * from test' cur = conn.cursor() cur.execute(sql) result = cur.fetchall()#获取查询结果 print(result) response = HttpResponse(content_type='application/vnd.ms-excel')#指定返回为excel文件 response['Content-Disposition'] = 'attachment;filename=test.xls'#指定返回文件名 wb = xlwt.Workbook(encoding = 'utf-8')#设定编码类型为utf8 sheet = wb.add_sheet(u'表格')#excel里添加类别 sheet.write(0,0,'id') sheet.write(0,1,'零件') sheet.write(0,2,'领用人') sheet.write(0,3,'领用时间') sheet.write(0,4,'其他') row = 1 for list in result: sheet.write(row,0, list['id']) sheet.write(row,1, list['robot_part']) sheet.write(row,2, list['part_get_people']) sheet.write(row,3, list['part_get_time']) sheet.write(row,4, list['others']) row=row + 1 output = BytesIO() wb.save(output) output.seek(0) response.write(output.getvalue()) return response前端组件代码
<el-button type="primary" @click="export_Xls()">导出</el-button> /*定义一个按钮*/ export_Xls(){ var a = document.createElement('a'); var url = '';//这里写上接口 var filename = 'data.xlsx';//下载的文件名 a.href=url; a.download = filename; a.click() }点击导出 完成下载