python實現查詢的數據寫入到excel


#coding=utf-8
import sys
import xlwt
import pymysql as MySQLdb #這里是python3 如果你是python2.x的話,import MySQLdb
import datetime


host = '192.168.10.109'
user = 'root'
pwd = ''
port = 3306
db = 'com66nao_mi'
sheet_name = 'report'
out_path = r'D:\SQL\aaa'+'.xls'
print(out_path)
sql = '''select * from mi_orgs;'''

def export():
conn = MySQLdb.connect(host,user,pwd,db,charset='utf8')
cursor = conn.cursor()
count = cursor.execute(sql)
print("查詢出" + str(count) + "條記錄")

#來重置游標的位置
cursor.scroll(0,mode='absolute')
#搜取所有結果
results = cursor.fetchall()

# 獲取MYSQL里面的數據字段名稱
fields = cursor.description
workbook = xlwt.Workbook() # workbook是sheet賴以生存的載體。
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)

#結果測試
if __name__=="__main__":
export()


免責聲明!

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



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