python3实现mysql导出excel的方法

yipeiwu_com6年前Python基础

Mysql中'employee'表内容如下:

# __Desc__ = 从数据库中导出数据到excel数据表中
import xlwt
import pymysql
class MYSQL:
  def __init__(self):
    pass
  def __del__(self):
    self._cursor.close()
    self._connect.close()
  def connectDB(self):
    """
    连接数据库
    :return:
    """
    try:
      self._connect = pymysql.Connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='123456',
        db='test',
        charset='utf8'
      )
      return 0
    except:
      return -1
  def export(self, table_name, output_path):
    self._cursor = self._connect.cursor()
    count = self._cursor.execute('select * from '+table_name)
    # print(self._cursor.lastrowid)
    print(count)
    # 重置游标的位置
    self._cursor.scroll(0, mode='absolute')
    # 搜取所有结果
    results = self._cursor.fetchall()
    # 获取MYSQL里面的数据字段名称
    fields = self._cursor.description
    workbook = xlwt.Workbook()
    # 注意: 在add_sheet时, 置参数cell_overwrite_ok=True, 可以覆盖原单元格中数据。
    # cell_overwrite_ok默认为False, 覆盖的话, 会抛出异常.
    sheet = workbook.add_sheet('table_'+table_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(output_path)
if __name__ == '__main__':
  mysql = MYSQL()
  flag = mysql.connectDB()
  if flag == -1:
    print('数据库连接失败')
  else:
    print('数据库连接成功')
    mysql.export('employee', 'E:/test_input.xls')

执行结果如下:

总结

以上所述是小编给大家介绍的python3实现mysql导出excel的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

python实现在IDLE中输入多行的方法

在python命令行模式下,在IDLE中输入多行,例如if  else 使用tab的方式,控制缩进 在最后,连续两个回车,表示结束 >>> if stat...

Python学习笔记之os模块使用总结

复制代码 代码如下: #!/usr/bin/env python ##-*- coding: utf-8 -*-   import os   print "n欢迎大家...

Python中Flask-RESTful编写API接口(小白入门)

Python中Flask-RESTful编写API接口(小白入门)

1.API接口:hello world 案例 from flask import Flask from flask_restful import Api, Resource app...

python基于SMTP协议发送邮件

本文实例为大家分享了python基于SMTP协议发送邮件的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*...

python中bs4.BeautifulSoup的基本用法

导入模块 from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html.parser") 下面看下常见的用...