Python中的openpyxl类型错误

2024-09-23 00:23:22 发布

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

我想根据工人的职业来确定他们的工资和税收。守则是:

import openpyxl as xl
wb = xl.load_workbook('Book1.xlsx')
sheet = wb['Sheet1']

dictionary = {
    'Boss': 1000,
    'Manager': 670,
    'Secretary': 300,
    'Accountant': 470,
    'Redactor': 590,
    'Chef': 270,
    'Servant': 170
}

for row in range(2, sheet.max_row + 1):
    profession = sheet.cell(row, 2)
    salary = dictionary.get(profession.value, profession.value)
    salary_cell = sheet.cell(row, 3)
    salary_cell.value = salary
    tax = salary * 0.14
    tax_cell = sheet.cell(row, 4)
    tax_cell.value = tax
    net_salary = salary - tax
    net_salary_cell = sheet.cell(row, 5)
    net_salary_cell.value = net_salary

wb.save('Book2.xlsx')

但我有一个错误:

tax = salary * 0.14 TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

然后我尝试将字典中的工资转换成字符串,并按如下方式编码:

wb = xl.load_workbook('Book1.xlsx')
sheet = wb['Sheet1']

dictionary = {
    'Boss': '1000',
    'Manager': '670',
    'Secretary': '300',
    'Accountant': '470',
    'Redactor': '590',
    'Chef': '270',
    'Servant': '170'
}

for row in range(2, sheet.max_row + 1):
    profession = sheet.cell(row, 2)
    salary = dictionary.get(profession.value)
    salary_cell = sheet.cell(row, 3)
    salary_cell.value = salary
    tax = int(salary) * 0.14
    tax_cell = sheet.cell(row, 4)
    tax_cell.value = tax
    net_salary = int(salary) - tax
    net_salary_cell = sheet.cell(row, 5)
    net_salary_cell.value = net_salary

wb.save('Book2.xlsx')

但现在:

tax = int(salary) * 0.14 TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

如何解决此错误


Tags: fornetdictionaryvalueloadcellxlsxsheet