簡體   English   中英

之后使用openpyxl將數據寫入excel中的列

[英]writing data to columns in excel with openpyxl after

再次返回...所以現在,我已經能夠使用openpyxl將數據提取到python中,並完成了計算,但是現在我仍然在如何將數據打印回另一張紙上。 下面僅將最后的總值打印到所引用的單元格,這顯然不是我希望得到的結果。 我需要增加行並將總值打印到excel文件中。 在B2,B3等中……在我的詞典中用個人的名字回“粗體”,然后將其打印到第三張紙上會更好,所以在A1:Ax和總B1中的名字是: Bx。 幫助到達任何一個將不勝感激! 謝謝

wb = openpyxl.load_workbook("Test_book.xlsx") 
sheet=wb.get_sheet_by_name('Hours')   
employee_names=[]
employee_hours=[]
for row in sheet['A']:
    employee_names.append(row.value)
for row in sheet['B']:
    employee_hours.append(row.value)
print(employee_names)
print(employee_hours)
my_dict=dict(zip(employee_names,employee_hours))
print(my_dict)

sheet2=wb.get_sheet_by_name('Rate')
employee_names2=[]
employee_Rate=[]

for row in sheet2['A']:
    employee_names2.append(row.value)
for row in sheet2['B']:
    employee_Rate.append(row.value)
print(employee_names2)
print(employee_Rate)

my_dict2=dict(zip(employee_names2,employee_Rate))
print(my_dict2)

sheet3=wb.get_sheet_by_name('payable')
#pulls key from dictionary, multiples it by other number
for row in sheet['A']:
    if row.value in my_dict:
        gross=(float(my_dict[row.value]*float(my_dict2[row.value])))       
        print(format(gross,'.2f'))
        sheet3.cell(row=2,column=2).value=gross

wb.save("Test_book.xlsx")

就我個人而言,我認為這確實應該在Excel本身中使用vlookup之類的功能完成。 無論哪種方式,您真正需要做的就是跟蹤您所在的行

...
sheet3=wb.get_sheet_by_name('payable')
#pulls key from dictionary, multiples it by other number
rownum = 2
for row in sheet['A']:
    if row.value in my_dict:
        gross=(float(my_dict[row.value]*float(my_dict2[row.value])))       
        print(format(gross,'.2f'))
        #put name in A
        sheet3.cell(row=rownum,column=1).value=row.value
        #put gross pay in B
        sheet3.cell(row=rownum,column=2).value=gross
        rownum += 1

wb.save("Test_book.xlsx")

此外,openpyxl支持數組索引樣式的單元格引用,這可以使事情更易於閱讀/編寫:

#these are equivalent
sheet.cell(row=1, column=1).value = value
sheet.['A1'] = value

您有時可能還會發現函數openpyxl.utils.get_column_letter()有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM