Python將MySQL表數據寫入excel


背景:將mysql表查詢結果寫入excel。

  1.使用sqlyog工具將查詢結果導出到Excel.xml中,用excel打開發現:因為text字段中有回車換行操作,顯示結果行是亂的。

  2.用mysql -uadmin -p -h -P -NBe"select * from tb;" >>a.txt 導出。發現用TXT查看還是excel查看也是亂序。

  3.下面是用Python的xlsxwriter模塊寫入excel文件。

數據庫表:

CREATE TABLE `s1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `local` text,
  `mobile` int(11) DEFAULT NULL,
  `CreateTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

表查詢:

local字段:text類型,里面有空格、空行,換行操作

----------------------------------------------------------------------------------------------------------------------------------

 

------------------------------------------------------------------------------------------------------------------------------------------

Python腳本內容:

[root@monitor2]# vim select.py
#!/usr/bin/env python
#-*- coding: utf8 -*-
import MySQLdb
import string
import xlsxwriter
import datetime

# 定義時間標志變量
sheet_time = datetime.datetime.now()
sheet_mark = sheet_time.strftime('%Y-%m-%d')
book_mark = sheet_time.strftime('%Y%m%d')

# 定義輸出excel文件名
workbook = xlsxwriter.Workbook('select_'+book_mark+'.xlsx')

# 定義sheet的名字
worksheet = workbook.add_worksheet(sheet_mark)

# 定義sheet中title的字體format
bold = workbook.add_format({'bold': True})

# 定義sql查詢命令
cmd="select * from db1.s1;"

# 定義鏈接mysql的用戶信息 字典
Loginfo = {'USER':'admin', 'PSWD':'admin', 'HOST':'10.10.60.105', 'PORT':4001}

# 調用MySQLdb模塊 鏈接 mysql
conn=MySQLdb.connect(host=Loginfo['HOST'],user=Loginfo['USER'],passwd=Loginfo['PSWD'],port=Loginfo['PORT'],charset='utf8')
cur=conn.cursor()
cur.execute(cmd)

# 查詢數據結果和字段名字 賦值給兩個變量
result = cur.fetchall()
fields = cur.description # get column name

# 將結果寫入excel中

# 定義title的坐標:row=0,col=0~字段總數 也就是excel的第一行:0,0  ~ 0,len(fields)

# 關於fields的結果如下圖:通過fields[field][0] 獲取字段名


for field in range(0,len(fields)):
    worksheet.write(0,field,fields[field][0],bold)

#數據坐標0,0 ~ row,col   row取決於:result的行數;col取決於fields的總數
for row in range(1,len(result)+1):
    for col in range(0,len(fields)):
        worksheet.write(row,col,u'%s' % result[row-1][col])
cur.close()
conn.close()
workbook.close()

輸出excel結果如下圖:

--------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------

點開Local:格式不亂

-------------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------------

 


免責聲明!

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



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