【问题标题】:writing data to columns in excel with openpyxl after之后使用openpyxl将数据写入excel中的列
【发布时间】:2017-11-28 20:21:52
【问题描述】:

又回来了…… 所以现在,我已经能够使用 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")

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    就个人而言,我认为这确实应该在 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() 很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 2016-05-07
      相关资源
      最近更新 更多