简体   繁体   English

使用 openpyxl 在 Excel 工作表中的单元格中搜索字符串

[英]Search a cell for a string in Excel sheet using openpyxl

I have some unnecessary rows in an Excel spreadsheet which I need to remove.我需要删除 Excel 电子表格中有一些不必要的行。 The Excel sheet always generates lines at the end of a report I wish to remove using openpyxl. Excel 工作表总是在我希望使用 openpyxl 删除的报告末尾生成行。 An example cell is Report Generated By: NAME一个示例单元格是Report Generated By: NAME

I have attempted this but am receiving an 'TypeError: argument of type 'NoneType' is not iterable' error.我已经尝试过了,但收到了“TypeError:'NoneType' 类型的参数不可迭代”错误。 Here is my code:这是我的代码:

import openpyxl as xl
import os
filename = "1615449726873.xlsx"

wb = xl.load_workbook(filename)
sheet = wb[os.path.splitext(filename)[0]]

for row in range(2, sheet.max_row +1):
    if 'Report Generated By  :' in sheet.cell(row, 1).value:
        sheet.delete_rows(row, 1)

wb.save("testing.xlsx")

I have had success in removing cells with == a string (see below), however, the sheet also has cells with have dynamic content so I need CONTAINS rather than is EQUAL TO to work as well.我已经成功地删除了带有 == 字符串的单元格(见下文),但是,工作表也有具有动态内容的单元格,所以我需要 CONTAINS 而不是 EQUAL TO 才能正常工作。 This code works:此代码有效:

for row in range(2, sheet.max_row +1):
    if sheet.cell(row, 1).value is == 'Report Generated On:':
        sheet.delete_rows(row, 1)

Can someone explain why the second example works but the first does not?有人可以解释为什么第二个示例有效,但第一个示例无效吗?

I think the problem is that empty cells are returning NoneType.我认为问题在于空单元格正在返回 NoneType。 You can get around that my casting the cell value as a string like this您可以解决我将单元格值转换为这样的字符串的问题

for row in range(2, sheet.max_row +1):
    if 'Report Generated By  :' in str(sheet.cell(row, 1).value):
        sheet.delete_rows(row, 1)

wb.save("testing.xlsx")

The problem is that you assume all cells have strings for values but they could be numbers, datetimes or None.问题是您假设所有单元格都有值字符串,但它们可能是数字、日期时间或无。

Also when deleting rows from the top of the worksheet your counter will become inaccurate, much better to do this from the bottom.此外,当从工作表顶部删除行时,您的计数器将变得不准确,最好从底部执行此操作。

for idx in range(sheet.max_row, 0, -1):
    cell = ws.cell(idx, 1)
    if cell.value and "Report Generated By  :" in cell.value:
        sheet.delete_rows(idx)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM