python 保存excel 文件
1,python 将数据库信息到处为excel。
使用模块xlwt,配合django, (xlwt 操作excel注意事项,数据不能超过65535,数据量小可以使用,数据量大应该使用openpyxl)
def excel_export(request): """ 导出excel表格 """ list_obj = Student.objects.all() if list_obj: # 创建工作薄 ws = Workbook(encoding='utf-8') w = ws.add_sheet(u"学生表") w.write(0, 0, "学号") w.write(0, 1, u"姓名") w.write(0, 2, u"性别") w.write(0, 3, u"出生日期") # 写入数据 excel_row = 1 for obj in list_obj: data_id = obj.sno data_user = obj.sname data_sex = obj.ssex data_birthday = obj.sbirthday.strftime("%Y-%m-%d") # obj.sbirthday.strftime("%Y-%m-%d") w.write(excel_row, 0, data_id) w.write(excel_row, 1, data_user) w.write(excel_row, 2, data_sex) w.write(excel_row, 3, data_birthday) excel_row += 1 # 方框中代码是保存本地文件使用,如不需要请删除该代码 ########################### exist_file = os.path.exists("test.xls") if exist_file: os.remove(r"test.xls") ws.save("test.xls") ############################ import io output = io.BytesIO() ws.save(output) response = HttpResponse(content_type='application/vnd.ms-excel')
#### xlsx 文件的content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response['Content-Disposition'] = 'attachment; filename=test.xls' response.write(output.getvalue()) return response
2,直接通过前端调用配置接口就自动下载excel文件了。
def static_img(request,path): # 返回图片文件 from pathlib import Path import mimetypes from django.utils.http import http_date full_path = Path(settings.IMG_PATH + "/"+path) content_type,encoding = mimetypes.guess_type(str(full_path)) static_obj = full_path.stat() response = FileResponse(full_path.open('rb'),content_type=content_type) response['Last-Modified'] = http_date(static_obj.st_mtime) return response