python对工作的帮助知乎_身为公务员或事业编的你,工作中会用到python吗?

本文介绍如何使用Python进行Excel数据处理及统计分析,通过连接数据库并执行SQL查询,快速获取销售商的数量、总重量和总价格等汇总信息,并将结果写入新的Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作以来,每天下午5点下班让我很不适应,也一度十分颓废。从4月开始做计划,具体到每天的某个时间段,发现还是自律一点的生活让人更舒服,先不扯这么多了,今天就举一个例子,说不定你正好也需要

首先把需要的excel文档上传(好像不支持excel),那我还是截图吧

比如我们有这么一个表格,有日期、销售商、来源省份、单价、入库量,一共有1845行数据

我们现在需要统计这么一个数据:

我们需要获取每类销售商的数量、总重量和总价格,如果用python来实现,写好代码之后,只需要几秒钟就能算出结果,结果如下:

我先把代码贴出来,有不明白的地方,咱们可以交流哈

import xlrd

import xlwt

from xlutils.copy import copy

import pymysql

database = pymysql.connect("127.0.0.1", "test", "test", "db", charset='utf8')

cursor = database.cursor()

sql = "SELECT company,count(company),sum(weight),sum(weight*price) FROM data GROUP BY company;"

cursor.execute(sql)

result = cursor.fetchall()

# print(result)

for i in result:

if i[0] == '王五小麦':

a_num = i[1]

a_weight = i[2]

a_total_price = i[3]

elif i[0] == '李四粮食':

b_num = i[1]

b_weight = i[2]

b_total_price = i[3]

elif i[0] == '张三粮配':

c_num = i[1]

c_weight = i[2]

c_total_price = i[3]

elif i[0] == '赵六麦子专营':

d_num = i[1]

d_weight = i[2]

d_total_price = i[3]

tem_excel = xlrd.open_workbook('D:/统计表_模板.xls', formatting_info=True)

tem_sheet = tem_excel.sheet_by_index(0)

new_excel = copy(tem_excel)

new_sheet = new_excel.get_sheet(0)

style = xlwt.XFStyle()

font = xlwt.Font()

font.name = '微软雅黑'

font.bold = True

font.height = 360

style.font = font

borders = xlwt.Borders()

borders.top = xlwt.Borders.THIN

borders.bottom = xlwt.Borders.THIN

borders.left = xlwt.Borders.THIN

borders.right = xlwt.Borders.THIN

style.borders = borders

alignment = xlwt.Alignment()

alignment.horz = xlwt.Alignment.HORZ_CENTER

alignment.vert = xlwt.Alignment.VERT_CENTER

style.alignment = alignment

new_sheet.write(2, 1, a_num, style)

new_sheet.write(2, 2, a_weight, style)

new_sheet.write(2, 3, a_total_price, style)

new_sheet.write(3, 1, b_num, style)

new_sheet.write(3, 2, b_weight, style)

new_sheet.write(3, 3, b_total_price, style)

new_sheet.write(4, 1, c_num, style)

new_sheet.write(4, 2, c_weight, style)

new_sheet.write(4, 3, c_total_price, style)

new_sheet.write(5, 1, d_num, style)

new_sheet.write(5, 2, d_weight, style)

new_sheet.write(5, 3, d_total_price, style)

new_excel.save('D:/8月下旬统计表.xls')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值