在工作中,我们可能会遇到把数据库数据导出成excel表的给甲方霸霸看的情况,所以这个技能是必备滴!
我在工作中用的是flask框架,用OptionMysql的方法来操作数据,详情可以看我之前的博客
进入正题:
第一步我们需要获取数据,先查询数据库并且遍历,例如:
# 获取数据
mysql = OptionMysql(mysql_option)
sql = "SELECT id,name,age FROM users WHERE is_delete=0"
result = mysql.get_data_dict(sql)
data = []
# 遍历数据
for row in result:
res = {
"id":row["id"],
"name":row["name"],
"age":row["age"]
}
data.append(res)
return data
第二步就是把获取到的数据导入excel表啦,我们需要用到xlwt来处理
from xlwt import Workbook # 导入xlwt 使用Workbook
wb = Workbook()
sheet1 = wb.add_sheet('Sheet1') # 决定execl表表页
sheet1.write(0, 0, "ID编码") # 对应第一列
sheet1.write(0, 1, "名字")
sheet1.write(0, 2, "年龄")
sheet1.write(0, 2, "性别")
for index, value in enumerate(data):
sheet1.write(index + 1, 0, value["id"])
sheet1.write(index + 1, 1, value["name"])
sheet1.write(index + 1, 2, value["age"])
sheet1.write(index + 1, 3, "")
# 判断路径是否存在
if not os.path.exists(os.path.join(BASE_PATH, 'static')):
os.mkdir(os.path.join(BASE_PATH, 'static'))
if not os.path.exists(os.path.join(BASE_PATH, 'static', 'download')):
os.mkdir(os.path.join(BASE_PATH, 'static', 'download')) # 生成路径
excel_name = 'users_list_' + str(int(time.time()*1000)) + '.xls' # 使用时间戳生成随机excel表名
filename = os.path.join(BASE_PATH, 'static', 'download', excel_name) # 生成方法
wb.save(filename)
# 生成的文件存储在static/download 路径下
数据库数据导出到excel表就完成啦!该方法在表头很多的时候就会出现代码繁多且臃肿的现象***(如果数据需要再次加工的时候简直吐血)***
所以除了xlwt处理之后,还有很多更好的方法,pandas库就是其中之一,有空的时候给大家分享一下~