继Python将数据库数据导入到EXCEL文章之后,这次来一个推进版,将其编写为函数,接着是class。哈哈。

     问过群里的朋友,他们大多采用工具将数据导入到excel,本人以前是用select ... into outfile 导出为csv格式,但是这样的数据是没有列标题的,每次手动添加。后来用过sqlyog 这个工具也没有列标题。后来改用Navicat,觉得以后可以过安稳日子啦,有一次新项目上线,运营要“全部”数据(真不知道他们怎么想的),用navicat 试了一次,慢的要死。还经常无故终止,真是恶心死我啦。

     对于导出“全部”数据,简单高效点。我决定用Python解析一次。中心思想是:用Python MySQLdb 模块 从Information_schema中得出数据内容的列标题,利用xlwt模块创建excel文件,并写入数据。下面贴出代码,欢迎各位拍砖:

#!/usr/bin/env python
import sys
import MySQLdb
import xlwt
db=sys.argv[1]
table=sys.argv[2]
def xls(sql='select * from %s.%s'):
    #xls info
    wbk=xlwt.Workbook()
    sheet=wbk.add_sheet('sheet 1')
    #connect Info
    try:
        conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='XXXXX')
        cursor=conn.cursor()
        cursor.execute('use information_schema')
        cursor.execute('select COLUMN_NAME  from COLUMNS where TABLE_NAME=%s and TABLE_SCHEMA=%s',(table,db))
        columnName=cursor.fetchall()
        columnLen=len(columnName)
        columnNum=0
        for data in range(columnLen):
                sheet.write(0,columnNum,columnName[columnNum][0])
                columnNum +=1
        cursor.execute(sql % (db,table))
        dataInfo=cursor.fetchall()
        rowLine=0
        for line in range(len(dataInfo)):
                lineInfo=dataInfo[line]
                rowLine+=1
                columnLine=0
                for row in lineInfo:
                        sheet.write(rowLine,columnLine,row)
                        columnLine+=1
        wbk.save('%s.xls' % table)
        cusor.close()
        conn.commit()
        conn.close()
    finally :
        conn.close()
        sys.exit(1)
if __name__=='__main__':
        xls()