作者:圊渘湜壞亾 | 来源:互联网 | 2024-12-18 18:42
前言:本文旨在为开发者提供一个实用的指南,通过具体的代码示例,介绍如何利用Python的xlwt模块结合pymysql库从MySQL数据库中提取数据,并将其保存到Excel文件中。此方法适用于需要定期导出数据报表的场景。
1 import pymysql, xlwt
2 def export_to_excel(table_name):
3 host, user, password, database = '118.24.3.40', 'jxz', '123456', 'jxz'
4 cOnnection= pymysql.connect(host=host, user=user, password=password, database=database, charset='utf8')
5 cursor = connection.cursor()
6 query = f'SELECT * FROM {table_name}.'
7 cursor.execute(query) # 执行SQL查询
8 fields = [field[0] for field in cursor.description] # 获取所有字段名
9 data_rows = cursor.fetchall() # 获取所有记录
10 workbook = xlwt.Workbook()
11 worksheet = workbook.add_sheet('Sheet1')
12 # 写入表头
13 for col, field in enumerate(fields):
14 worksheet.write(0, col, field)
15 row_index = 1 # 控制行号
16 for row_data in data_rows:
17 for col, cell_value in enumerate(row_data):
18 worksheet.write(row_index, col, cell_value)
19 row_index += 1 # 每写完一行,行号加1
20 workbook.save(f'{table_name}.xls') # 保存Excel文件
21 export_to_excel('app_student')