码迷,mamicode.com
首页 > 数据库 > 详细

python3实现mysql导出excel

时间:2018-05-05 11:21:01      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:blog   absolute   put   password   sheet   python   xls   导出   结果   

转载:tingzuhuitou

# coding:utf8
import sys
# __Desc__ = 从数据库中导出数据到excel数据表中

import xlwt
import pymysql


def export(host, user, password, dbname, table_name,output_path):
    conn = pymysql.connect(host, user, password, dbname, charset=utf8)
    cursor = conn.cursor()
    print(cursor.rownumber)

    count = cursor.execute(select * from +table_name)
    print(cursor.rownumber)
    print(cursor.lastrowid)
    print(count)
    # 重置游标的位置
    cursor.scroll(0,mode=absolute)
    print(cursor.rownumber)
    # 搜取所有结果
    results = cursor.fetchall()

    # 获取MYSQL里面的数据字段名称
    fields = cursor.description
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet(table_+table_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(output_path)


# 结果测试
if __name__ == "__main__":
    export(localhost, root, 123456, test, test_input, E:/test_input.xls)

 

python3实现mysql导出excel

标签:blog   absolute   put   password   sheet   python   xls   导出   结果   

原文地址:https://www.cnblogs.com/fuqia/p/8993843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!