python_excel_openpyxl模糊查询excel中某个单元格的位置

该代码示例展示了如何利用Python的openpyxl库读取Excel文件,并查找特定关键词。首先加载xlsx文件,获取所有工作表名称,然后遍历第一个工作表的每一行和每个单元格,检查单元格值是否为非空,如果找到包含关键词的单元格,打印其值、行号和列号。
摘要由CSDN通过智能技术生成
from openpyxl import load_workbook


def search_value(filename,keyword):
    wb = load_workbook(filename)
    all_sheets = wb.get_sheet_names()
    print(all_sheets)
    sheet = wb.get_sheet_by_name(all_sheets[0])
    for row in sheet.iter_rows():
        for cell in row:
            if cell.value is not None:
                info = cell.value.find(keyword)
                if info == 0:
                    print(cell.value)
                    print(cell.row)
                    print(cell.column)




if __name__ == '__main__':

    try:
        filename='test.xlsx'
        keyword='存货'
        search_value(filename,keyword)
        print('   Finish')
    except Exception as e:
        print(e)




  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用openpyxl库可以读取单元格字体颜色,具体步骤如下: 1. 导入openpyxl库和颜色模块 ```python from openpyxl import load_workbook from openpyxl.styles import colors from openpyxl.styles import Font, Color ``` 2. 打开excel文件,获取工作簿和活动表单对象 ```python wb = load_workbook('example.xlsx') sheet = wb.active ``` 3. 循环遍历单元格,获取每个单元格的字体颜色 ```python for row in sheet.iter_rows(): for cell in row: font = cell.font color = font.color if isinstance(color, colors.Color): r, g, b = color.rgb print(f'The color of cell {cell.coordinate} is RGB({r}, {g}, {b})') else: print(f'The color of cell {cell.coordinate} is {color.theme}') ``` 上述代码,我们使用了`iter_rows()`方法来遍历所有行,然后在每一行遍历所有单元格。对于每个单元格,我们获取它的字体对象和颜色属性,并判断颜色是否为RGB格式。如果是,就打印出RGB值,否则打印出颜色的主题。 需要注意的是,如果单元格的字体颜色是自定义的颜色,则无法获取其RGB值,只能获取到颜色的主题。 完整代码示例: ```python from openpyxl import load_workbook from openpyxl.styles import colors from openpyxl.styles import Font, Color wb = load_workbook('example.xlsx') sheet = wb.active for row in sheet.iter_rows(): for cell in row: font = cell.font color = font.color if isinstance(color, colors.Color): r, g, b = color.rgb print(f'The color of cell {cell.coordinate} is RGB({r}, {g}, {b})') else: print(f'The color of cell {cell.coordinate} is {color.theme}') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值