当前位置:   article > 正文

python输出数据到excel-Python从数据库导出数据到Excel

python从数据库导出excel如果没有提示

#coding=utf-8

import pymysql

import xlwt

import importlib,sys

importlib.reload(sys)

# __author__ = 'itechzero'

# __date__ = '2018/02/26'

# __Desc__ = 从数据库中导出数据到excel数据表中

def export(host,user,password,dbname,table_name,outputpath):

conn = pymysql.connect(host,user,password,dbname,charset='utf8')

cursor = conn.cursor()

count = cursor.execute('select * from '+table_name)

print(count)

# 重置游标的位置

cursor.scroll(0,mode='absolute')

# 搜取所有结果

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(outputpath)

# 结果测试

if __name__ == "__main__":

export('localhost','root','test','test','user',r'foo.xls')

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/967379
推荐阅读
相关标签
  

闽ICP备14008679号