利用python将mysql中的数据导入excel
Python对Excel的读写主要有xlrd、xlwt、xlutils、openpyxl、xlsxwriter几种。
如下分别利用xlwt和openpyxl将mysql数据库中查询的数据保存到excel中(注意:xlwt不支持.xlsx文件):
一、从mysql查询数据
import mysql.connector
conn=mysql.connector.connect(host='xx.xx.xx.xx',user='root', passwd='password', db='test')
cursor = conn.cursor()
sql = 'select * from table1 limit 5'
cursor.execute(sql)
datas=cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
print(datas)
二、分别利用xlwt和openpyxl将datas数据保存到excel
1、xlwt写入数据示例代码
import xlwt def set_style(name, height, bold = False): style = xlwt.XFStyle() #初始化样式 font = xlwt.Font() #为样式创建字体 font.name = name font.bold = bold font.color_index = 4 font.height = height style.font = font return style def write_excel(datas,filename): #创建工作簿 workbook = xlwt.Workbook(encoding='utf-8') #创建sheet data_sheet = workbook.add_sheet('demo') row0 = [u'地市', u'country', '时间', '温度','湿度','雨量','风速'] for i in range(len(row0)): data_sheet.write(0, i, row0[i], set_style('Times New Roman', 220, True)) nrows=len(datas) for i in range(nrows): for j in range(len(row0)): data_sheet.write(i+1,j,datas[i][j]) # 工作簿保存到磁盘 workbook.save(filename)
2、openpyxl写入数据示例代码
from openpyxl.workbook import Workbook from openpyxl.utils import get_column_letter from openpyxl.styles import Font def write_excel_openpyxl1(datas,filename): # 在内存创建一个工作簿obj wb = Workbook() # 将workbook obj写到excel文件 # ew = ExcelWriter(workbook=wb) ew=wb.active # 设定第一个sheet页,好像第一个sheet只能这样设定 ws = wb.worksheets[0] ws.title=u'天气' # 向第一个sheet页写数据吧 i = 1 for line in datas: for col in range(1,len(line)+1): ColNum = get_column_letter(col) ws.cell('%s%s'%(ColNum,i)).value = line[col-1] i += 1 # 工作簿保存到磁盘 wb.save(filename) def write_excel_openpyxl(datas,filename): # 在内存创建一个工作簿obj result_wb = Workbook() #第一个sheet是ws ws1 = result_wb.worksheets[0] # ws1=wb1.create_sheet('result',0) #设置ws的名称 ws1.title = "天气" row0 = [u'地市', u'country', '时间', '温度','湿度','雨量','风速'] ft = Font(name='Arial', size=11, bold=True) for k in range(len(row0)): ws1.cell(row=1,column=k+1).value=row0[k] ws1.cell(row=1,column=k+1).font=ft for i in range(1,len(datas)+1): for j in range(1,len(row0)+1): # col=get_column_letter(j) # ws1.cell('%s%s'%(col,i)).value='%s' % (data[j-1]) ws1.cell(row=i+1,column=j).value=datas[i-1][j-1] # 工作簿保存到磁盘 result_wb.save(filename = filename)
三、调用函数
write_excel_openpyxl(datas,'result.xlsx') write_excel_openpyxl1(datas,'result1.xlsx') write_excel(datas,'result2.xls')
结果保存到.xlsx和.xls文件中,完成!