简述Vue+Django下载xlsx表格
可在此连接中查看如何生成xlsx文件
url.py
path('auditInfo/downloadTable', auditViews.downloadAuditTable, name='downloadAuditTable'),
api.js
export const downloadAuditTable = params=>{
return axios({
method: 'post',
//此url用来生成文件,并将文件存储至服务器上。
url: '/auditInfo/downloadTable',
data: qs.stringify(params),
responseType: 'blob'
})
}
生成xlsx表格并将文件存储在服务器上
import xlsxwriter
def downloadAuditTable(request):
if request.method == 'POST':
response = {}
try:
path_Name = 'test.xlsx'
# 存储的路径及文件名
workbook = xlsxwriter.Workbook('media/'+path_Name)
# 定义基本样式
base_style = workbook.add_format({"align": "left",'border': 0, 'font_size': 12,'text_wrap': 1,'valign': 'vcenter'})
# 定义表格中的文本内容为自动换行格式
base_style.set_text_wrap()
headings = ['姓名','1的数量','2的数量']
data = [['A',12,10],['B',12,15],['C',12,20],['D',12,25]]
# 创建一个工作表,名为sheetOne
worksheet = workbook.add_worksheet("sheetOne")
# 合并单元格
worksheet.merge_range('A1:C2', 'Mytable')
worksheet.write_row("A3",headings,base_style)
# 将第一列设为红色(此处仅为了展示如何定义单个单元格样式的例子)
for row in range(0,len(data)):
for col in range(0,len(data[row])):
if col==0:
worksheet.write(row+3, col, data[row][col], workbook.add_format({"fg_color": "red",'border': 1, 'font_size': 12,'text_wrap': 1,'valign': 'vcenter'}))
else:
worksheet.write(row+3, col, data[row][col],base_style)
workbook.close()
file = open('media/' + path_Name, 'rb')
response = StreamingHttpResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{}"'.format(path_Name)
except Exception as e:
print(traceback.format_exc(limit=1))
return response
vue页面下载文件
import{
...
downloadAuditTable,
...
}
methods: {
dataURLtoBlob(encoded){
const dataBlob = new Blob([encoded]);
return window.URL.createObjectURL(dataBlob);
},
//我的点击事件会调用downloadTable方法
downloadTable(){
downloadAuditTable(params).then(response => {
if(response.statusText=="OK"){
let downloadURL = this.dataURLtoBlob(response.data)
let anchor = document.createElement("a")
//下载时显示的文件名(自定义)
anchor.download = 'myDownloadFile.xlsx'
anchor.href = downloadURL
anchor.click()
that.$message({type: 'success', message: '下载成功!'})
that.downloadLoading = false
}
}).catch(function (error) {
console.log(error);
that.$message({type: 'error', message: '请检查网络!'})
that.downloadLoading = false
});
},
}