数据库数据导出CSV文件,浏览器下载
直接上代码:
def download(request):
# 从数据库查询数据
data_list = Info.objects.all() # 定义返回对象
response = HttpResponse()
# 给返回对象定义解析类型
response['Content-Type'] = 'csv'
# 声明一个csv的响应
response['Content-Disposition'] = 'attachment;filename="data.csv"'
# csv的响应编码格式声明
response.write(codecs.BOM_UTF8) # 把响应设置成文件句柄
writer_obj = csv.writer(response)
# 先写入表格头
writer_obj.writerow(["姓名", "年龄", "地址"])
# 写入数据
for info in data_list:
writer_obj.writerow([info.name, info.age, info.address]) return response
参考1:
https://www.cnblogs.com/haoshine/p/5695760.html
import csv
import codecs
import datetime
from django.db import connection
from django.contrib.auth.models import User
from django.http import HttpResponse
from models import * def output(request, user_id, node_id, function_id):
function_id = int(function_id)
user_id = int(user_id)
node_id= int(node_id) # 指定csv请求回应
response = HttpResponse(content_type='text/csv') user = User.objects.get(id=user_id)
functions_has_permission = DataPermission.objects.filter(category=node_id) # 取出sql语句
function_obj = DataPermission.objects.get(id=function_id)
function_obj_sql = function_obj.sql # 执行sql语句,并执行。保存执行结果和字段名
cursor = connection.cursor()
cursor.execute(function_obj_sql)
results = cursor.fetchall() descriptions = cursor.description
descriptions_long = len(descriptions)
description_list = [None] * descriptions_long
i = 0
for description in descriptions:
description_list[i] = description[0]
i = i + 1 # 将执行结果从元组形式转化为列表形式。
i=0
results_long = len(results)
results_list = [None] * results_long
for i in range(results_long):
results_list[i] = list(results[i])
# print(results_list) # 为文件取名字
now = datetime.datetime.now()
now = str(now.isoformat())
name = (now + '.csv').replace(':', '') # 声明一个csv的响应
response['Content-Disposition'] = 'attachment; filename="%s"' % name
# csv的响应的编码格式声明
response.write(codecs.BOM_UTF8)
writer = csv.writer(response) # 转码问题
a = u'中'
for result in results_list:
i=0
for item in result:
if type(item) == type(a):
# 如果是unicode类型,那么编码成utf-8
result[i] = item.encode('utf-8')
i = i + 1
# with open(response, 'wb') as f:
writer.writerow(description_list)
for result in results_list:
writer.writerow(result)
i = i + 1
response.close()
return response
参考
导出的文件,中文如果显示成乱码
解决方法:将上面代码中的'utf-8' 改成 'gb2312'
result[i] = item.encode('gb2312')
参考2:
抽取数据库文件: def exportmysql(request):
conn= MySQLdb.connect(
host='192.168.137.3',
port = 3306,
user='root',
passwd='',
db ='DEVOPS',
charset='UTF8'
)
cur = conn.cursor()
a = cur.execute("select ip,info,env from machine_info")
info = cur.fetchall()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
writer = csv.writer(response)
for row in info:
writer.writerow(row)
return response
参考3:
最近一个用django开发的web项目要进行数据的导入导出,所以有必要了解下。
django中主要用HttpResponse将请求结果返回给浏览器,所以文件的下载也是通过改对象进行处理的,具体的一个列子的代码如下:
[python] view plain copy
#文件下载
def download(request):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
""" #读取mongodb的文件到临时文件中
fileid_=request.GET["fileid"]
filepath_ = ('%s/%s'%(MEDIA_ROOT, fileid_)) #文件全路径
file_=TFiles.objects.get(fileid=int(fileid_))
filename_=file_.filename
filetype_=file_.filetype if os.path.isfile(filepath_):
pass
else:
mongoLoad(fileid_) #下载文件
def readFile(fn, buf_size=262144):#大文件下载,设定缓存大小
f = open(fn, "rb")
while True:#循环读取
c = f.read(buf_size)
if c:
yield c
else:
break
f.close()
response = HttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM') #设定文件头,这种设定可以让任意文件都能正确下载,而且已知文本文件不是本地打开
response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8') + filetype_.encode('utf-8')#设定传输给客户端的文件名称
response['Content-Length'] = os.path.getsize(filepath_)#传输给客户端的文件大小
return response
=====================
Python+Django实现文件的下载
HttpResponse, StreamingHttpResponse, FileResponse
https://blog.csdn.net/li627528647/article/details/77544136
数据库数据导出CSV文件,浏览器下载的更多相关文章
- C#将DataTable数据导出CSV文件
C#将DataTable数据导出CSV文件通用方法! //导出按钮调用导出方法 protected void btnCSV_Click(object sender, EventArgs e) ...
- 从数据库中导出.csv文件
需求: 本次将数据库中的数据导出成.csv文件(office可以打开), //数据的生成,根据你所选中的数据进行生成 //params:$activity_id -> 活动的id //param ...
- 彻底理解使用JavaScript 将Json数据导出CSV文件
前言 将数据报表导出,是web数据报告展示常用的附带功能.通常这种功能都是用后端开发人员编写的.今天我们主要讲的是直接通过前端js将数据导出Excel的CSV格式的文件. 原理 首先在本地用Excel ...
- Java导出页面数据或数据库数据至Excel文件并下载,采用JXL技术,小demo(servlet实现)
public class ExportExcelServlet extends HttpServlet { /** * */ private static final long serialVersi ...
- DataTable数据导出CSV文件
public static void SaveAsExcel(DataTable dt1) { //System.Windows.Forms.SaveFileDialog sfd = new Syst ...
- java web 读取数据库数据写入Excel返回浏览器下载
@RequestMapping(value = "/download", method = RequestMethod.GET) public void downstudents( ...
- l如何把SQLServer表数据导出CSV文件,并带列名
http://jingyan.baidu.com/article/4b07be3c466b5d48b280f37f.html 微信公众号:
- PHP导出数据到CSV文件函数/方法
如果不清楚什么是CSV文件,可看如下文章介绍 CSV格式的是什么文件?CSV是什么的缩写? /** * 导出数据到CSV文件 * @param array $data 数据 * @param arr ...
- mysql 导出数据到csv文件的命令
1.导出本地数据库数据到本地文件 mysql -A service_db -h your_host -utest -ptest mysql> select * from t_apps where ...
随机推荐
- 【page-monitor 前端自动化 上篇】初步调研
转载文章:来源(靠谱崔小拽) 前端自动化测试主要在于:变化快,不稳定,兼容性复杂:故而,想通过较低的成本维护较为通用的自动化case比较困难.本文旨在通过page-monitor获取和分析dom结构, ...
- python之道05
1.写代码,有如下列表,按照要求实现每一个功能 li = ["alex", "WuSir", "ritian", "barry&q ...
- Bluefruit LE Sniffer - Bluetooth Low Energy (BLE 4.0) - nRF51822 驱动安装及使用
BLE Sniffer https://www.adafruit.com/product/2269 Bluefruit LE Sniffer - Bluetooth Low Energy (BLE 4 ...
- python面向对象(C3算法)(六)
1. 了解python2和python3类的区别 python2在2.3之前使用的是经典类, 2.3之后, 使用的是新式类 2. 经典类的MRO 树形结构的深度优先遍历 -> 树形结构遍历 cl ...
- Python中threading的join和setDaemon的区别[带例子]
python的进程和线程经常用到,之前一直不明白threading的join和setDaemon的区别和用法,今天特地研究了一下.multiprocessing中也有这两个方法,同样适用,这里以thr ...
- 菜鸟的《Linux程序设计》学习——MySQL数据库安装、配置及基本操作
1. MySQL数据库: 在涉及到一些大型的Web系统或者嵌入式软件的开发时,都少不了用数据库来管理数据.在Windows操作系统下,使用过各种各样的数据库,如:sqlServer.Oracle.My ...
- The North American Invitational Programming Contest 2018 H. Recovery
Consider an n \times mn×m matrix of ones and zeros. For example, this 4 \times 44×4: \displaystyle \ ...
- Java基础知识:集合框架
*本文是最近学习到的知识的记录以及分享,算不上原创. *参考文献见链接. 目录 集合框架 Collection接口 Map接口 集合的工具类 这篇文章只大致回顾一下Java的总体框架. 集合框架 ht ...
- Java-字符转比较
实用的字符串比较方法 package com.tj; public class MyClass implements Cloneable { public static void main(Strin ...
- Python第三方库之openpyxl(11)
Python第三方库之openpyxl(11) Stock Charts(股票图) 在工作表上按特定顺序排列的列或行中的数据可以在股票图表中绘制.正如其名称所暗示的,股票图表通常被用来说明股价的波动. ...