我的openpyxl代码似乎无法正常工作

2024-04-29 06:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前面临的挑战是编写一些代码,这些代码执行以下操作:

  • 接受将被指定为batchNumber

  • 接受将被指定为batchLocation

  • 查看名为customerData

  • 将用户输入batchNumber与第一列中的数据匹配

  • batchLocation写入第三列中与batchNumber相邻的单元格

我认为这比我想象的要容易得多,但我似乎在兜圈子

excel文档的结构为

Batch Number Product Type Location

1234 Guitar *Blank*

2345 Drums *Blank*

我尝试过从excel部分修改ATBS代码,但似乎无法让它与用户输入一起工作,而不是使用字典中的数据。代码运行时没有错误,但除非数据出现在第一行,否则不会进行更改?我也尝试过使用iter_rows(),但没有太大的成功

import openpyxl

wb = openpyxl.load_workbook('customerData.xlsx')
sheet = wb['SalesOrders']

# User Input of data 
CUSTOMER_UPDATE = {}
batchNumber = str(input('Please scan the batch number: '))
batchLocation = input('Please scan the location: ')
CUSTOMER_UPDATE[batchNumber] = batchLocation

# Loop through the rows and update the location
for rowNum in range(2, sheet.max_row): #Used to skip the first row as it is only a header.
    productName = sheet.cell(row=rowNum, column=1).value

if productName in CUSTOMER_UPDATE:
    sheet.cell(row=rowNum, column=3).value = CUSTOMER_UPDATE[productName]

wb.save('customerDataCopy.xlsx')

Tags: the数据代码用户updatecustomerexcelsheet
1条回答
网友
1楼 · 发布于 2024-04-29 06:57:16

我认为您需要为每一行测试productName,因此您需要在for循环下缩进if,如下所示:

# Loop through the rows and update the location
for rowNum in range(2, sheet.max_row): #Used to skip the first row as it is only a header.
    productName = sheet.cell(row=rowNum, column=1).value
    if productName in CUSTOMER_UPDATE:
        sheet.cell(row=rowNum, column=3).value = CUSTOMER_UPDATE[productName]

相关问题 更多 >