python3实现mysql导出excel

来源:互联网 发布:金亚洲软件下载 编辑:程序博客网 时间:2024/06/04 18:15

一、准备工作

1.1win7下Python工具库安装xlwt和xlrd的安装

1.1.1方法一:下载安装

1、从http://pypi.python.org/pypi/xlwt 下载 xlwt-1.0.0.tar.gz;
2、从http://pypi.python.org/pypi/xlrd下载 xlrd-0.9.4.tar.gz;
3、将包解压缩;
4、在win7下运行,
[plain] view plain copy
cmd
切换到对应的解压缩路径
[plain] view plain copy
F:
cd xlrd-0.9.4
5、安装
[plain] view plain copy
setup.py install
xlwt同理。

1.1.2方法二: 命令提示符(推荐)

Python3可以在 命令提示符中 输入

pip3 install xlrdpip3 install xlwt

  Python2直接输入

pip install xlrdpip install xlwt

1.2windows系统python35 安装mysql-python

搜索半天,最终发现,python3不支持mysql-python了,多么痛的领悟啊!!!
安装第三方包pymysql。
下载地址:https://pypi.python.org/pypi/PyMySQL#downloads

使用方法:
import pymysql as MySQLdb

二、代码实现

# coding:utf8  import sys  import xlwt  #import MySQLdbimport pymysql as MySQLdbimport datetime  host = '主机地址'  user = 'root'  pwd = '密码'  db = '数据库名'  sql = 'select * from 表格'  sheet_name = 'building'  out_path = '..\data\data_excel\one.xls'conn = MySQLdb.connect(host,user,pwd,db,charset='utf8')  cursor = conn.cursor()  count = cursor.execute(sql)  print(count)  cursor.scroll(0,mode='absolute')  results = cursor.fetchall()  fields = cursor.description  workbook = xlwt.Workbook()  sheet = workbook.add_sheet(sheet_name,cell_overwrite_ok=True)  for field in range(0,len(fields)):      sheet.write(0,field,fields[field][0])  row = 1  col = 0  for row in range(1,len(results)+1):      for col in range(0,len(fields)):          sheet.write(row,col,u'%s'%results[row-1][col])  workbook.save(out_path)

三、python3实现mysql导出TXT

代码比较简单,需要完善

# coding=utf-8  '''''  main function:主要实现把txt中的每行数据写入到excel中 '''  #################  #第一次执行的代码  import xlwt #写入文件  import xlrd #打开excel文件  fopen=open("..\data\\data_txt\\a.txt",'r',encoding = 'utf-8')  lines=fopen.readlines()  #新建一个excel文件  file=xlwt.Workbook(encoding='utf-8',style_compression=0)  #新建一个sheet  sheet=file.add_sheet('data')  ############################  #写入写入a.txt,a.txt文件有20000行文件  i=0  for line in lines:      sheet.write(i,0,line)      i=i+1  #################################  #第二层执行代码,写入b.txt,"""j=20001 #从20001行写入  fopen2=open("e:\\a\\bb\\b.txt",'r')  lines2=fopen2.readlines()  for line in lines2:      sheet.write(j,0,line)      j=j+1"""file.save('minni.xls')  
原创粉丝点击