直接上代码:

  1. def download(request):
  2. # 从数据库查询数据
  3. data_list = Info.objects.all()
  4.  
  5. # 定义返回对象
  6. response = HttpResponse()
  7. # 给返回对象定义解析类型
  8. response['Content-Type'] = 'csv'
  9. # 声明一个csv的响应
  10. response['Content-Disposition'] = 'attachment;filename="data.csv"'
  11. # csv的响应编码格式声明
  12. response.write(codecs.BOM_UTF8)
  13.  
  14. # 把响应设置成文件句柄
  15. writer_obj = csv.writer(response)
  16. # 先写入表格头
  17. writer_obj.writerow(["姓名", "年龄", "地址"])
  18. # 写入数据
  19. for info in data_list:
  20. writer_obj.writerow([info.name, info.age, info.address])
  21.  
  22. return response

参考1:

https://www.cnblogs.com/haoshine/p/5695760.html

  1. import csv
  2. import codecs
  3. import datetime
  4. from django.db import connection
  5. from django.contrib.auth.models import User
  6. from django.http import HttpResponse
  7. from models import *
  8.  
  9. def output(request, user_id, node_id, function_id):
  10. function_id = int(function_id)
  11. user_id = int(user_id)
  12. node_id= int(node_id)
  13.  
  14. # 指定csv请求回应
  15. response = HttpResponse(content_type='text/csv')
  16.  
  17. user = User.objects.get(id=user_id)
  18. functions_has_permission = DataPermission.objects.filter(category=node_id)
  19.  
  20. # 取出sql语句
  21. function_obj = DataPermission.objects.get(id=function_id)
  22. function_obj_sql = function_obj.sql
  23.  
  24. # 执行sql语句,并执行。保存执行结果和字段名
  25. cursor = connection.cursor()
  26. cursor.execute(function_obj_sql)
  27. results = cursor.fetchall()
  28.  
  29. descriptions = cursor.description
  30. descriptions_long = len(descriptions)
  31. description_list = [None] * descriptions_long
  32. i = 0
  33. for description in descriptions:
  34. description_list[i] = description[0]
  35. i = i + 1
  36.  
  37. # 将执行结果从元组形式转化为列表形式。
  38. i=0
  39. results_long = len(results)
  40. results_list = [None] * results_long
  41. for i in range(results_long):
  42. results_list[i] = list(results[i])
  43. # print(results_list)
  44.  
  45. # 为文件取名字
  46. now = datetime.datetime.now()
  47. now = str(now.isoformat())
  48. name = (now + '.csv').replace(':', '')
  49.  
  50. # 声明一个csv的响应
  51. response['Content-Disposition'] = 'attachment; filename="%s"' % name
  52. # csv的响应的编码格式声明
  53. response.write(codecs.BOM_UTF8)
  54. writer = csv.writer(response)
  55.  
  56. # 转码问题
  57. a = u'中'
  58. for result in results_list:
  59. i=0
  60. for item in result:
  61. if type(item) == type(a):
  62. # 如果是unicode类型,那么编码成utf-8
  63. result[i] = item.encode('utf-8')
  64. i = i + 1
  65. # with open(response, 'wb') as f:
  66. writer.writerow(description_list)
  67. for result in results_list:
  68. writer.writerow(result)
  69. i = i + 1
  70. response.close()
  71. return response

参考

导出的文件,中文如果显示成乱码

解决方法:将上面代码中的'utf-8' 改成 'gb2312'

  1. result[i] = item.encode('gb2312')

参考2:

  1. 抽取数据库文件:
  2.  
  3. def exportmysql(request):
  4. conn= MySQLdb.connect(
  5. host='192.168.137.3',
  6. port = 3306,
  7. user='root',
  8. passwd='',
  9. db ='DEVOPS',
  10. charset='UTF8'
  11. )
  12. cur = conn.cursor()
  13. a = cur.execute("select ip,info,env from machine_info")
  14. info = cur.fetchall()
  15. response = HttpResponse(content_type='text/csv')
  16. response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
  17. writer = csv.writer(response)
  18. for row in info:
  19. writer.writerow(row)
  20. return response

参考3:

最近一个用django开发的web项目要进行数据的导入导出,所以有必要了解下。

django中主要用HttpResponse将请求结果返回给浏览器,所以文件的下载也是通过改对象进行处理的,具体的一个列子的代码如下:

  1. [python] view plain copy
  2. #文件下载
  3. def download(request):
  4. """
  5. Send a file through Django without loading the whole file into
  6. memory at once. The FileWrapper will turn the file object into an
  7. iterator for chunks of 8KB.
  8. """
  9.  
  10. #读取mongodb的文件到临时文件中
  11. fileid_=request.GET["fileid"]
  12. filepath_ = ('%s/%s'%(MEDIA_ROOT, fileid_)) #文件全路径
  13. file_=TFiles.objects.get(fileid=int(fileid_))
  14. filename_=file_.filename
  15. filetype_=file_.filetype
  16.  
  17. if os.path.isfile(filepath_):
  18. pass
  19. else:
  20. mongoLoad(fileid_)
  21.  
  22. #下载文件
  23. def readFile(fn, buf_size=262144):#大文件下载,设定缓存大小
  24. f = open(fn, "rb")
  25. while True:#循环读取
  26. c = f.read(buf_size)
  27. if c:
  28. yield c
  29. else:
  30. break
  31. f.close()
  32. response = HttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM') #设定文件头,这种设定可以让任意文件都能正确下载,而且已知文本文件不是本地打开
  33. response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8') + filetype_.encode('utf-8')#设定传输给客户端的文件名称
  34. response['Content-Length'] = os.path.getsize(filepath_)#传输给客户端的文件大小
  35. return response

=====================

Python+Django实现文件的下载

HttpResponse,  StreamingHttpResponse,  FileResponse

https://blog.csdn.net/li627528647/article/details/77544136

数据库数据导出CSV文件,浏览器下载的更多相关文章

  1. C#将DataTable数据导出CSV文件

    C#将DataTable数据导出CSV文件通用方法! //导出按钮调用导出方法    protected void btnCSV_Click(object sender, EventArgs e)   ...

  2. 从数据库中导出.csv文件

    需求: 本次将数据库中的数据导出成.csv文件(office可以打开), //数据的生成,根据你所选中的数据进行生成 //params:$activity_id -> 活动的id //param ...

  3. 彻底理解使用JavaScript 将Json数据导出CSV文件

    前言 将数据报表导出,是web数据报告展示常用的附带功能.通常这种功能都是用后端开发人员编写的.今天我们主要讲的是直接通过前端js将数据导出Excel的CSV格式的文件. 原理 首先在本地用Excel ...

  4. Java导出页面数据或数据库数据至Excel文件并下载,采用JXL技术,小demo(servlet实现)

    public class ExportExcelServlet extends HttpServlet { /** * */ private static final long serialVersi ...

  5. DataTable数据导出CSV文件

    public static void SaveAsExcel(DataTable dt1) { //System.Windows.Forms.SaveFileDialog sfd = new Syst ...

  6. java web 读取数据库数据写入Excel返回浏览器下载

    @RequestMapping(value = "/download", method = RequestMethod.GET) public void downstudents( ...

  7. l如何把SQLServer表数据导出CSV文件,并带列名

    http://jingyan.baidu.com/article/4b07be3c466b5d48b280f37f.html 微信公众号:

  8. PHP导出数据到CSV文件函数/方法

    如果不清楚什么是CSV文件,可看如下文章介绍  CSV格式的是什么文件?CSV是什么的缩写? /** * 导出数据到CSV文件 * @param array $data 数据 * @param arr ...

  9. mysql 导出数据到csv文件的命令

    1.导出本地数据库数据到本地文件 mysql -A service_db -h your_host -utest -ptest mysql> select * from t_apps where ...

随机推荐

  1. [Android 测试] 压力稳定性测试之: Monkey 详解分析脚本(转载)

    一.什么是稳定性测试? 通过随机点击屏幕一段时间,看看app会不会奔溃,能不能维持正常运行. 二. Money是什么? Monkey测试是Android平台自动化测试的一种手段,通过Monkey程序模 ...

  2. 后台返回平铺数据,如何转换成树形json并渲染树形结构,ant tree 异步加载

    如何后台返回对象数组(平铺式) 1.根据字段标识(板块)获取根节点 ### initTreeData(dataOrg){ var resultArr=dataOrg[0] var secArr=[]; ...

  3. hibernate3缓存(hibernate)

    一级缓存:当应用程序调用Session 的save() .update() .savaeOrUpdate() .get() 或load() ,以及调用查询接口的list() .iterate() 或f ...

  4. shell脚本,计算从0+2+4+6+....100的结果是多少?

    [root@localhost wyb]# cat evenjia.sh #!/bin/bash #从0++++...100的结果 i= ` do sum=$(($sum+i)) i=$(($i+)) ...

  5. Protocol(协议)、Delegate(委托)、DataSource(数据源)

    这里以 UITableViewController 和 UITableView 的关系为例: //--------------------------------------------------- ...

  6. jq相关操作

    1事件: <div class="ele">123</div> box.onclick = function(ev){ ev:系统传入的事件对象 ele.i ...

  7. 在 shell中, 我們可用 $0, $1, $2, $3 ... 這樣的变量分別提取命令行中变量

    代码: script_name parameter1 parameter2 parameter3 ...我們很容易就能猜出 $0 就是代表 shell script 名称(路径)本身,而 $1 就是其 ...

  8. stm32单片机的C语言优化

    对于有些单片机,自身容量是很有限的,有的仅仅只有8k.16k的flash等,但是对32位mcu来说,这点空间实在有点小.不像计算机一样内存和rom都很多,因此有时候就需要进行代码优化.大家都知道,单片 ...

  9. sublime text 3搭建python 的ide

    感谢大佬-->原文链接 1. 打开Sublime text 3 安装package control Sublime Text 3 安装Package Control 2. 安装 SublimeR ...

  10. 【19】javascript有哪些方法定义对象

    创建Object的方式有4种. 方式一: 通过对象字面量表示法(又称为直接量.原始方式). var obj = {name:"moyu"}; 方式二: 通过new和构造函数Obje ...