这篇文章将为大家详细讲解有关python3怎么实现mysql导出excel,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
python的五大特点:1.简单易学,开发程序时,专注的是解决问题,而不是搞明白语言本身。2.面向对象,与其他主要的语言如C++和Java相比, Python以一种非常强大又简单的方式实现面向对象编程。3.可移植性,Python程序无需修改就可以在各种平台上运行。4.解释性,Python语言写的程序不需要编译成二进制代码,可以直接从源代码运行程序。5.开源,Python是 FLOSS(自由/开放源码软件)之一。
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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。