|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 makliu 于 2023-5-16 09:39 编辑
如题, df 的 数据如果 存在中文, 那么中文 就会显成乱码, 这个要怎么解决??
views代码如下
- def export_excel(request):
- try:
- tableName = "tttt"
- df = pd.DataFrame([["1", "我是谁", "甘呈"], ["2", "你是谁", "甘要呈"]], columns=['id', 'name', 'age'])
- response = HttpResponse()
- response['Content-Type'] = 'application/vnd.ms-excel'
- response['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(tableName)
- response['Accept-Encoding'] = 'gzip, deflate, br'
- out = _convert_df_to_bytes(df)
- if not out:
- raise RuntimeError("xxx")
- response.write(out.getvalue())
- return response
- except Exception as e:
- return e
- def _convert_df_to_bytes(df):
- output = io.BytesIO() # todo 50M nginx
- df.to_csv(output, index=False, encoding="utf8")
- output.seek(0)
- return output
复制代码
ajax 代码如下:
- // 导出按钮
- function bindExport(){
- $("#btn_export").click(function () {
- var queryParams = {"arg1": "xxx", "arg2": "yyy"};
-
- var xhr = new XMLHttpRequest();
- var url = "/export_excel/";
- xhr.responseType = "arraybuffer";
- xhr.open("get", url, true);
- xhr.onload = function () {
- const blob = new Blob([this.response], {type:"application/vnd.ms-excel"});
- if(blob.size < 1) {
- alert('导出失败,导出的内容为空!');
- return;
- }
- if(window.navigator.msSaveOrOpenBlob) {
- navigator.msSaveOrOpenBlob(blob, 'test.xls')
- } else {
- const aLink = document.createElement('a');
- aLink.style.display = 'none';
- aLink.href = window.URL.createObjectURL(blob);
- aLink.download = 'test.xls';
- document.body.appendChild(aLink);
- aLink.click();
- document.body.removeChild(aLink);
- return;
- }
- }
- xhr.setRequestHeader("Authorization", "xxx");
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.send(JSON.stringify(queryParams));
-
- });
- };
复制代码
这样导出是 中文是乱码, 这要怎么解决??? |
|