「編程」python自動辦公——Excel自動生成統計報表

「編程」python自動辦公——Excel自動生成統計報表

import xlrd
import xlwt
from xlutils.copy import copy
x1sx=x1rd.open_workbook('d:/7月下句入庫表.xlsx)
table=x1sx.sheet_by_index(4)
all_data=[]
for n in range(1,table.nrows): //nrows為excel中的行
company=table.cell(n,1).value
price=table.cell(n,3).value
weight= table.cel1(n,4).value
data={'company':company,'weight':weight,'price':price)
all_data.append(data)
#以下內容可以用pandas的groupby輕易實現,這裡不引入新知識,使用一個笨辦法a_weight=[]
a_total_price=[]
b weight=[]
b_total_price=[]
c_weight=[]
c_total_price=[]
d_weight=[]
d_total_price=[]
//循環統計
for i in all data:
if i['company']=='張三糧配':
a_weight.append(i['weight'])
a_total_price.append(i['weight']*i['price'])
if it'company']=='李四糧食':
b_weight,append(i['weight])
b_total_price.append(i['weight']*i['price'])
if i[company']=='王五小麥':
c_weight.append(i['weight])
c_total_price.append(i['weight']*i['price'])
if i['company']==‘趙六麥子專營”:
d_weight.append(i['weight])
d_total_price.append(i['weight']*i['price'])
//新建表
tem_excel=x1rd.open_workbook("D:/統計表_模板.x1s',formatting_info=True)
tem_sheet=tem_excel.sheet_by_index(0)
new_excel=copy(tem_excel)
new_sheet=new_excel.get_sheet(0)
style=x1wt.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, len(a_weight), style)
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)
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)
new sheet. write(4,2, round(sum(c_weight),2), style)
new_sheet. write(4,3, round(sum(c_total_price),2), style)
new_sheet. write(5,1, len(d_weight), style)
new_sheet. write(5,2, round(sum(d_weight),2), style)
new_sheet. write(5,3, round(sum(d_total_price),2), style)


分享到:


相關文章: