将mysql中的表导出_Python将mysql中表导出为Excel表格

需求:Python将mysql中表导出为Excel表格

mysql表中的数据:

59a7501b19aa2a18fd1dab6f606f7ac0.png

测试环境:

平台:Windows10、centos7

python版本:python3.7(以下脚本兼容python2)

python库安装:

pip install pymysql

pip install MySQLdb

pip install xlwt

新建py——python_mysql_excel.py

# coding: utf-8

# author: sirxy

# created_time: 2020/12/23

import sys

import xlwt

# 当前的python版本

if sys.version_info >= (3, 0):

import pymysql as mysql

else:

import MySQLdb as mysql

# mysql信息

host = '127.0.0.1'

port = 3306

user = 'root'

passwd = 'sirxy'

db = 'ceshi'

charset = 'utf8'

# 连接mysql,获取cursor

conn = mysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)

cursor = conn.cursor()

table = 'runoob_w3cnote'

count = cursor.execute("select * from {table};".format(table=table))

print(count)

# 重置游标的位置

cursor.scroll(0, mode='absolute')

# 拿到该条SQL所有结果

results = cursor.fetchall()

print(results)

# 拿到该表里面的字段名称

fields = cursor.description

print(fields)

workbook = xlwt.Workbook()

sheet = workbook.add_sheet(table, 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)):

value = results[row - 1][col]

if not value:

value = ''

sheet.write(row, col, '%s' % value)

workbook.save(r'./{db}_{table}.xlsx'.format(db=db, table=table))

运行代码,输出成果:

cac15b87d94cb9b2e40dbd38e62f4962.png

打开即可看到文件内容:

f1da5941cc6b0c4ab73b94793ceec500.png

以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值