openpyxl:如果描述中有短语,如何获取单元格总数?
openpyxl: How to get total of cells if there is a phrase in the description?
完全是 python 和 openpyxl 的新手,感谢您的帮助:
我有一个电子表格,记录我的收入和支出,包括日期、描述、借方和贷方金额。
我想使用 openpyxl 来自动化添加特定类别中的值的过程。
示例数据:
My spreadsheet
假设我想知道我在发放工资上花了多少钱,我找到包含 "wages" 的单元格,然后将总数加起来。
这是我到目前为止编写的代码,我不知道如何 select 单元格和总计。
import openpyxl as xl
wb = xl.load_workbook('sampledata.xlsx')
sheet = wb['Sheet1']
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 2)
total = 0
search_phrase = "Wage"
if cell.value is None:
continue
else:
if search_phrase in cell.value:
total = float(cell.value) + total
total_cell = sheet.cell(5, 5)
total_cell.value = total
wb.save("sampledata2.xlsx")
感谢您的帮助! :)
假设我正确理解了您的问题,您只需更改两点即可完成这项工作:
首先,您需要在 for
循环之前移动 total = 0
。实际上,每次您转到新行时,总数都会重置为 0。
增加总数时,您需要添加 "Debit" 列中的值,而不是 "Description." 因此,您需要 total += float(cell.offset(column=2).value)
。 (对于 total = total + ...
,+=
是 shorthand)
您还可以将带有 total_cell
的两行代码从 for
循环中取出(只是取消缩进),这样它们只会在循环完成后执行。
另一件事:您的搜索短语目前区分大小写。如果你想让它适用于大小写的任意组合,请使用 if search_phrase.casefold() in str(cell.value).casefold()
.
完全是 python 和 openpyxl 的新手,感谢您的帮助: 我有一个电子表格,记录我的收入和支出,包括日期、描述、借方和贷方金额。 我想使用 openpyxl 来自动化添加特定类别中的值的过程。
示例数据: My spreadsheet
假设我想知道我在发放工资上花了多少钱,我找到包含 "wages" 的单元格,然后将总数加起来。
这是我到目前为止编写的代码,我不知道如何 select 单元格和总计。
import openpyxl as xl
wb = xl.load_workbook('sampledata.xlsx')
sheet = wb['Sheet1']
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 2)
total = 0
search_phrase = "Wage"
if cell.value is None:
continue
else:
if search_phrase in cell.value:
total = float(cell.value) + total
total_cell = sheet.cell(5, 5)
total_cell.value = total
wb.save("sampledata2.xlsx")
感谢您的帮助! :)
假设我正确理解了您的问题,您只需更改两点即可完成这项工作:
首先,您需要在
for
循环之前移动total = 0
。实际上,每次您转到新行时,总数都会重置为 0。增加总数时,您需要添加 "Debit" 列中的值,而不是 "Description." 因此,您需要
total += float(cell.offset(column=2).value)
。 (对于total = total + ...
,+=
是 shorthand)
您还可以将带有 total_cell
的两行代码从 for
循环中取出(只是取消缩进),这样它们只会在循环完成后执行。
另一件事:您的搜索短语目前区分大小写。如果你想让它适用于大小写的任意组合,请使用 if search_phrase.casefold() in str(cell.value).casefold()
.