Python的一个mysql实例

按公司名统计一定时期内入货的总车数,总重量还有总价格。数据表如下:

要用到的库是pymysql,读取excel表格的xlrd,写入excel的xlwt和复制excel模板的xlutils,代码如下:

  1 '''
  2     #一个pymysql的实例
  3     #将mysql数据库里的数据统计到excel表格
  4 '''
  5 #开始导入需要用到的模块
  6 import xlrd
  7 import xlwt
  8 from xlutils.copy import copy
  9 import pymysql
 10 
 11 #连接数据库
 12 database = pymysql.connect('localhost','databaseusername','databasepassword','databasename',charset='utf8')
 13 #初始化数据库连接指针
 14 cursor = database.cursor()
 15 #查询数据库
 16 sql = "SELECT company, COUNT(company), SUM(weight), SUM(price * weight) from data GROUP BY company;"
 17 #执行sql语句
 18 cursor.execute(sql)
 19 #将查询到的结果进行存储
 20 result = cursor.fetchall()
 21 #打印看结果是否符合预期
 22 print(result)
 23 
 24 #开始遍历元组result并分别存储各项数值
 25 for i in result:
 26     print(i)
 27     if i[0] == "张三粮配":
 28         a_che = i[1]
 29         a_dun = i[2]
 30         a_total_price = i[3]
 31     if i[0] == "李四粮食":
 32         b_che = i[1]
 33         b_dun = i[2]
 34         b_total_price = i[3]
 35     if i[0] == "王五小麦":
 36         c_che = i[1]
 37         c_dun = i[2]
 38         c_total_price = i[3]
 39     if i[0] == "赵六麦子专营":
 40         d_che = i[1]
 41         d_dun = i[2]
 42         d_total_price = i[3]
 43 
 44 #以带格式的方式导入工作簿模板
 45 tem_excel = xlrd.open_workbook('模板路径',formatting_info=True)
 46 #获取工作簿里的工作表
 47 tem_sheet = tem_excel.sheet_by_index(0)
 48 
 49 #复制模板
 50 new_excel = copy(tem_excel)
 51 #获取复制后的工作表
 52 new_sheet = new_excel.get_sheet(0)
 53 
 54 #定义写入总格式
 55 style = xlwt.XFStyle()
 56 #定义写入的字体格式
 57 font = xlwt.Font()
 58 font.name = "微软雅黑"
 59 font.bold = True
 60 font.height = 360
 61 #将字体格式写入到总样式
 62 style.font = font
 63 
 64 #定义写入的边框样式
 65 borders = xlwt.Borders()
 66 borders.top = xlwt.Borders.THIN
 67 borders.right = xlwt.Borders.THIN
 68 borders.bottom = xlwt.Borders.THIN
 69 borders.left = xlwt.Borders.THIN
 70 #将边框样式写入总样式
 71 style.borders = borders
 72 
 73 #开始定义对齐样式
 74 alignment = xlwt.Alignment()
 75 alignment.horz = xlwt.Alignment.HORZ_CENTER
 76 alignment.vert = xlwt.Alignment.VERT_CENTER
 77 #将对齐样式写入总样式
 78 style.alignment = alignment
 79 
 80 #开始向新的工作表里按要求写入数据
 81 #先写张三的,张三的在第三行,第二到第四列
 82 new_sheet.write(2, 1, a_che, style)
 83 new_sheet.write(2, 2, a_dun, style)
 84 new_sheet.write(2, 3, a_total_price, style)
 85 
 86 #再写李四的,李四的在第四行,第二到第四列
 87 new_sheet.write(3, 1, b_che, style)
 88 new_sheet.write(3, 2, b_dun, style)
 89 new_sheet.write(3, 3, b_total_price, style)
 90 
 91 #再写王五的,王五的在第五行,第二到第四列
 92 new_sheet.write(4, 1, c_che, style)
 93 new_sheet.write(4, 2, c_dun, style)
 94 new_sheet.write(4, 3, c_total_price, style)
 95 
 96 #再写赵六的,赵六的在第六行,第二列到第五列
 97 new_sheet.write(5, 1, d_che, style)
 98 new_sheet.write(5, 2, d_dun, style)
 99 new_sheet.write(5, 3, d_total_price, style)
100 
101 #最后保存工作簿
102 new_excel.save("存储路径/文件名称.xls")

效果如下:

原文地址:https://www.cnblogs.com/mafu/p/13924643.html