级别:初学者
为什么我得到"can't multiply sequence by non-int of type 'float'“错误?
import openpyxl as xl
wb = xl.load_workbook('transaction.xlsx')
sheet = wb['Sheet1']
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_price
wb.save('transaction1.xlsx')我正在导入transaction.xlsx文件。
发布于 2020-10-19 10:23:29
这是因为price列中的值包含$符号,这意味着该列中的所有值都是strings。为了将它们转换成floats,只需使用.replace方法删除$符号,并将它们type cast到floats中。这就是你怎么做的:
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
new_price = cell.value
new_price = float(new_price.replace("$","")) * 0.9
new_price_cell = sheet.cell(row, 4)
new_price_cell.value = new_pricehttps://stackoverflow.com/questions/64420150
复制相似问题