python操作Excel文件
参考:
- http://www.cnblogs.com/tianyajuanke/p/4048844.html
- http://blog.chinaunix.net/uid-24701781-id-3347590.html
- http://www_pythontab_com/html/2013/pythonhexinbiancheng_0314/298.html
使用到的模块:xlwt,StringIO
以下代码转自---http://www.cnblogs.com/tianyajuanke/p/4048844.html
objs = Units.objects.all() # 创建 Workbook 时,如果需要写入中文,请使用 utf-8 编码,默认是 unicode 编码。 wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('配件价格') ws.write(0, 0, '配件编号') ws.write(0, 1, '配件名称') ws.write(0, 2, '配件价格') ws.write(0, 3, '商场') excel_row = 1 for obj in objs: ws.write(excel_row, 0, obj.unitid) ws.write(excel_row, 1, obj.unitname) ws.write(excel_row, 2, obj.price) ws.write(excel_row, 3, obj.marketid) excel_row = excel_row + 1 # ------ 开始:这段代码可以用下面注释段替代,都是本应保存为文件格式的改成保存为数据流,以便返回前端下载 response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=example.xls' wb.save(response) return response # ------ 结束 """ sio = StringIO.StringIO() wb.save(sio) response = HttpResponse(sio.getvalue(),content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=test.xls' return response """
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步