django页面导出excel
2024-10-19 15:24:11
from django.http import HttpResponse from xlwt import *
from io import BytesIO
def excel_export(request): """ 导出excel表格 """ list_obj = Comment.objects.all().order_by("-time") if list_obj: # 创建工作薄 ws = Workbook(encoding='utf-8') w = ws.add_sheet(u"数据报表第一页") w.write(, , "id") w.write(, , u"用户名") w.write(, , u"发布时间") w.write(, , u"内容") w.write(, , u"来源") # 写入数据 excel_row = for obj in list_obj: data_id = obj.id data_user = obj.username data_time = obj.time.strftime(] data_content = obj.content dada_source = obj.source w.write(excel_row, , data_id) w.write(excel_row, , data_user) w.write(excel_row, , data_time) w.write(excel_row, , data_content) w.write(excel_row, , dada_source) excel_row += # 检测文件是够存在 # 方框中代码是保存本地文件使用,如不需要请删除该代码 ########################### exist_file = os.path.exists("test.xls") if exist_file: os.remove(r"test.xls") ws.save("test.xls") ############################ sio = BytesIO() ws.save(sio) sio.seek() response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=test.xls' response.write(sio.getvalue()) return response
请求指定链接并返回结果时出现 TypeError: string argument expected, got 'bytes' 错误
经过排查问题出现在使用StringIO的write方法上,用BytesIO替代StringIO即可解决问题
最新文章
- powerdesigner使用之——从“概念模型”到“物理模型”
- iOS设备中WiFi、蓝牙和飞行模式的开启与关闭
- 解压版tomcat设置为系统服务
- C--运算符,表达式和语句实例
- 单源最短路径问题-Dijkstra算法
- SpringBoot(四)之thymeleaf的使用
- 关于Redis数据库 ---- 基础篇
- Python3系列__01Python安装
- Entity Framework入门教程(15)---DbContext追踪实体状态改变
- js数组中容易误用的一些方法
- ueditor的简单用法
- windows7时间同步设置
- DOM&;BOM
- mysql 命令行快速将数据库转移到另一个服务器中(数据库备份还原)
- Unity3D实践系列06,球体撞击物体游戏
- Qt5_qt.conf
- html的css选择器
- Qt5_pro_02
- hive 数据导入
- 数据降维(Dimensionality reduction)