我正在从事一项需要写入csv并在前端下载的任务。在我已经完成的视图中:
...omitted details
data = data.values(*values_fields)
response = HttpResponse(content_type='text/csv')
writer = csv.DictWriter(response, fieldnames=values_fields)
writer.writeheader()
writer.writerows(data)
return response
而且,在前端:
let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const blob = new Blob(res, {type: "text/csv"});
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'data.csv';
a.click();
window.URL.revokeObjectURL(url);
a.remove()
首先,当我检查res时,我只看到了整数数组,而不是字典。如何下载我的数据?
我发现我得到的响应是UTF-16编码的数组。我应该将其解码为UTF-8->有意义的字符串,然后下载。
答案 0 :(得分:0)
不确定这是否是最好的解决方案,但这是我用Excel工作表完成的方法:
我将生成的文件保存到服务器中,然后在Django视图中执行此操作:
let vStack = UIStackView(frame: .zero)
vStack.axis = .vertical
vStack.alignment = .leading
vStack.translatesAutoresizingMaskIntoConstraints = false
addSubview(vStack)
if #available(iOS 11.0, *) {
vStack.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor).isActive = true
vStack.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor).isActive = true
} else {
vStack.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor).isActive = true
vStack.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor).isActive = true
}
vStack.topAnchor.constraint(equalTo: topAnchor, constant: 48).isActive = true
vStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -40).isActive = true
在我的React前端中,我使用js-file-download将文件下载到用户的计算机上。