说明见 思维导图

image.png
import xlrd
import xlwt
from xlutils.copy import copy
old_excel=xlrd.open_workbook('D:/7月下旬入库表.xlsx')
table=old_excel.sheet_by_index(0)
#列表操作,读取Excel数据到列表
all_data=[]
for i in range(1,table.nrows): #table.nrows整个EXCEL的行数
company=table.cell(i,1).value
price=table.cell(i,3).value
weight=table.cell(i,4).value
data={'company':company,'price':price,'weight':weight} #定义一个字典
all_data.append(data) #将字典的数据放到列表里
#定义几个列表
a_weight=[]
a_total_price=[]
b_weight=[]
b_total_price=[]
c_weight=[]
c_total_price=[]
d_weight=[]
d_total_price=[]
for n in all_data: #all_data代表列表所有数据
if n['company']=='张三的': #取列表中数据 与张三对比,注意是两个==
a_weight.append(n['weight']) #取大列表数据添加到新的列表变量
a_total_price.append(n['weight']*n['price'])
if n['company']=='里斯': #取列表中数据 与张三对比,注意是两个==
b_weight.append(n['weight']) #取大列表数据添加到新的列表变量
b_total_price.append(n['weight']*n['price'])
if n['company']=='王五': #取列表中数据 与张三对比,注意是两个==
c_weight.append(n['weight']) #取大列表数据添加到新的列表变量
c_total_price.append(n['weight']*n['price'])
#下面开始 操作目标表格
tem_excel=xlrd.open_workbook('d:/7月模板.xls',formatting_info=True) #打开目标表格,且打开其格式,注意是xls,若是xlsx,要另存为xls
tem_table=tem_excel.sheet_by_index(0) #打开目标表
#开始copy表
new_excel=copy(tem_excel) #等于新建了一个工作簿 相当于new_excel=XLWT.WORKBOOK()
new_sheet=new_excel.get_sheet(0) #新建一个copy表
#设置新表的格式
style=xlwt.XFStyle()
font=xlwt.Font()
font.name='微软雅黑'
font.bold=True
font.height=18*20
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,len(a_weight),style) #len(a_weight)这个列表中的元素个数
new_sheet.write(2,2,round(sum(a_weight),2),style)
new_sheet.write(2,3,round(sum(a_total_price),2),style)
new_sheet.write(3,1,len(b_weight),style) #len(a_weight)这个列表中的元素个数
new_sheet.write(3,2,round(sum(b_weight),2),style)
new_sheet.write(3,3,round(sum(b_total_price),2),style)
new_sheet.write(4,1,len(c_weight),style) #len(a_weight)这个列表中的元素个数
new_sheet.write(4,2,round(sum(c_weight),2),style)
new_sheet.write(4,3,round(sum(c_total_price),2),style)
new_excel.save('d:/ok.xls')