使用 openpyxl python 两列或多列的总和
Sum of two or more column using openpyxl python
我想要使用 openpyxl python 模块的 sheet 中超过 100 行的两列或更多列的总和。
下面是代码示例
for m in range(0,100):
sheet.cell(row=m+1,column=5).value=(sheet.cell(row=m+1,column=3).value) + (sheet.cell(row=m+1,column=4))
但是没有用。
请建议任何其他仅使用 openpyxl 的方法作为我的其他循环和使用 openpyxl 函数的代码部分。
您忘记获取第 4 列的 value
属性。
这应该可以解决您的问题:
for m in range(0, 100):
col3_value = sheet.cell(row=m + 1, column=3).value
col4_value = sheet.cell(row=m + 1, column=4).value
sheet.cell(row=m + 1, column=5).value = col3_value + col4_value
最好使用这样的函数:
import openpyxl
def val(x, y):
return sheet_obj.cell(row=x, column=y).value
path = "test.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
for m in range(1, 11):
sheet_obj.cell(row=m, column=3).value = val(m, 1) + val(m, 2)
wb_obj.save(path)
test.xlsx 文件:
输出:
我想要使用 openpyxl python 模块的 sheet 中超过 100 行的两列或更多列的总和。 下面是代码示例
for m in range(0,100):
sheet.cell(row=m+1,column=5).value=(sheet.cell(row=m+1,column=3).value) + (sheet.cell(row=m+1,column=4))
但是没有用。 请建议任何其他仅使用 openpyxl 的方法作为我的其他循环和使用 openpyxl 函数的代码部分。
您忘记获取第 4 列的 value
属性。
这应该可以解决您的问题:
for m in range(0, 100):
col3_value = sheet.cell(row=m + 1, column=3).value
col4_value = sheet.cell(row=m + 1, column=4).value
sheet.cell(row=m + 1, column=5).value = col3_value + col4_value
最好使用这样的函数:
import openpyxl
def val(x, y):
return sheet_obj.cell(row=x, column=y).value
path = "test.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
for m in range(1, 11):
sheet_obj.cell(row=m, column=3).value = val(m, 1) + val(m, 2)
wb_obj.save(path)
test.xlsx 文件:
输出: