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

时间:2020-02-11 21:49:47

标签: python openpyxl

我当前的挑战是编写执行以下操作的代码:

  • 接受将被指定为batchNumber

  • 的用户输入
  • 接受将被指定为batchLocation

  • 的用户输入
  • 浏览名为customerData的.xlsx文件中的每一行

  • 将用户输入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')

1 个答案:

答案 0 :(得分:0)

我认为您想为每行测试productName,所以您想在if循环下缩进for,如下所示:

# 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]