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将MySQL表数据写入excel

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

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] 获取字段名

Python将MySQL表数据写入excel
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结果如下图:

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

Python将MySQL表数据写入excel

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

点开Local:格式不乱

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

Python将MySQL表数据写入excel

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