使用python脚本从数据库导出数据到excel

python从数据库导出数据到excel

最近需要从数据库里导出一些数据到excel,刚开始我是使用下面的命令

select * from xxx where xxx into outfile 'xxx.xls'



结果报错

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

除了这个错误,可能还会报access deny的错误,关于access deny的错误,有一篇博客讲的很详细:https://daizj.iteye.com/blog/2174972

请教同事后发现他们都是用脚本来导出数据,这样安全又方便,于是自己也整了一个,记录一下


1)安装easy_install

由于公司使用的是老旧的python2,所以还是使用easy)install来安装包,如果没有安装easy_install,需要安装easy_install

yum install python-setuptools


2)安装pymysql和xlwt

使用easy_install安装pymysql和xlwt

easy_install pymysql
easy_install xlwt


使用pip也可以安装

pip install pymysql
pip isntall xlwt


使用pip安装如果报错

Fatal error in launcher: Unable to create process using '"C:\Python27\python.exe" "C:\Python27\Scripts\pip.exe" install pymysql'



可以将在前面加上python2 -m (启动python环境)

python2 -m pip install pymysql


3)编写脚本

# --*-- coding:utf8 --*--
import pymysql, xlwt


def export_excel(table_name):
    # 连接数据库,查询数据
    host, user, passwd, db='127.0.0.1','root','123','xxx'
    conn = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset='utf8')
    cur = conn.cursor()
    sql = 'select * from %s' % table_name
    cur.execute(sql)  # 返回受影响的行数
    
    fields = [field[0] for field in cur.description]  # 获取所有字段名
    all_data = cur.fetchall()  # 所有数据
    
    # 写入excel
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    
    for col,field in enumerate(fields):
        sheet.write(0,col,field)
    
    row = 1
    for data in all_data:
        for col,field in enumerate(data):
            sheet.write(row,col,field)
        row += 1
    book.save("%s.xls" % table_name)
    

if __name__ == '__main__':
    export_excel('app1_book')


4)启动脚本导出数据

python2 export.py

猜你喜欢

转载自www.cnblogs.com/zzliu/p/python.html