office:python 讀取excel

說明見 思維導(dǎo)圖


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數(shù)據(jù)到列表
all_data=[]
for i in range(1,table.nrows):   #table.nrows整個(gè)EXCEL的行數(shù)
    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} #定義一個(gè)字典
    all_data.append(data) #將字典的數(shù)據(jù)放到列表里


#定義幾個(gè)列表
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代表列表所有數(shù)據(jù)
    if n['company']=='張三的':         #取列表中數(shù)據(jù) 與張三對(duì)比,注意是兩個(gè)==
        a_weight.append(n['weight'])  #取大列表數(shù)據(jù)添加到新的列表變量
        a_total_price.append(n['weight']*n['price'])
    if n['company']=='里斯':         #取列表中數(shù)據(jù) 與張三對(duì)比,注意是兩個(gè)==
        b_weight.append(n['weight'])  #取大列表數(shù)據(jù)添加到新的列表變量
        b_total_price.append(n['weight']*n['price'])
    if n['company']=='王五':         #取列表中數(shù)據(jù) 與張三對(duì)比,注意是兩個(gè)==
        c_weight.append(n['weight'])  #取大列表數(shù)據(jù)添加到新的列表變量
        c_total_price.append(n['weight']*n['price'])

#下面開始 操作目標(biāo)表格
tem_excel=xlrd.open_workbook('d:/7月模板.xls',formatting_info=True)  #打開目標(biāo)表格,且打開其格式,注意是xls,若是xlsx,要另存為xls 
tem_table=tem_excel.sheet_by_index(0)  #打開目標(biāo)表

#開始copy表
new_excel=copy(tem_excel)  #等于新建了一個(gè)工作簿 相當(dāng)于new_excel=XLWT.WORKBOOK()
new_sheet=new_excel.get_sheet(0)  #新建一個(gè)copy表

#設(shè)置新表的格式
style=xlwt.XFStyle()

font=xlwt.Font()
font.name='微軟雅黑'
font.bold=True
font.height=18*20
style.font=font

#設(shè)置框線
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

#設(shè)置對(duì)齊
alignment=xlwt.Alignment()
alignment.horz=xlwt.Alignment.HORZ_CENTER
alignment.vert=xlwt.Alignment.VERT_CENTER
style.alignment=alignment


#開始往新單元格寫數(shù)據(jù)
new_sheet.write(2,1,len(a_weight),style)  #len(a_weight)這個(gè)列表中的元素個(gè)數(shù)
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)這個(gè)列表中的元素個(gè)數(shù)
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)這個(gè)列表中的元素個(gè)數(shù)
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')




?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容