Python將mysql中表導出為Excel表格


需求:Python將mysql中表導出為Excel表格

mysql表中的數據:
在這里插入圖片描述

測試環境:
平台: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))

運行代碼,輸出成果:

在這里插入圖片描述

打開即可看到文件內容:

在這里插入圖片描述

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM