【问题标题】:Using xlwings to open excel sheet. Need to search a string and print full line使用 xlwings 打开 excel 工作表。需要搜索字符串并打印整行
【发布时间】:2020-06-03 07:03:42
【问题描述】:

我正在使用 xlwings 打开 Excel 工作表。需要在特定列中搜索字符串并打印没有搜索项的字符串的整行,直到换行(\n)。输出应该在同一张表的新列中。

输入:

搜索字符串:[游戏] 输出:

【问题讨论】:

    标签: python excel string pandas xlwings


    【解决方案1】:
    import xlwings as xw
    

    使用xlwings打开excel文件

    filename = r'input.xlsx'
    book = xw.Book(filename)
    sheet = book.sheets[0]
    

    在本例中从column 'A' 的特定范围内找到sheetlast row

    lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
    

    为您将搜索的string 和您的输出所在的column 声明一个单独的变量。

    search_string = '[game]'
    sheet.range('B1').value = 'output'
    output_index = 2
    

    现在循环遍历该范围以查看您的 search_string 是否在该范围内

    for i in range(1, lrow + 1):
        if search_string in str(sheet.range('A{}'.format(i)).value):
            temp = str(sheet.range('A{}'.format(i)).value)
            temp = temp.split(search_string)[1]
            if '[' in temp:
                temp = temp.split('[')[0]
            sheet.range('B{}'.format(output_index)).value = temp
            output_index += 1
    
    
    book.save()
    book.close()
    

    下面是完整代码>>

    import xlwings as xw
    filename = r'input.xlsx'
    
    book = xw.Book(filename)
    sheet = book.sheets[0]
    lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
    search_string = '[game]'
    sheet.range('B1').value = 'output'
    output_index = 2
    
    for i in range(1, lrow + 1):
        if search_string in str(sheet.range('A{}'.format(i)).value):
            temp = str(sheet.range('A{}'.format(i)).value)
            temp = temp.split(search_string)[1]
            if '[' in temp:
                temp = temp.split('[')[0]
            sheet.range('B{}'.format(output_index)).value = temp
            output_index += 1
    
    
    book.save()
    book.close()
    

    【讨论】:

    • 感谢您的回复。以下是您的代码的输出: list output "[game] chess [person] kum" "chess [person] kum" "[Team] india [game] cricket [person]dho" "[Team] india cricket [person]dho "
    • 它不会删除 [game] 同一单元格的行下方。我只想要“ chess ”,但我得到“ chess [person] kum
    • 代码已编辑,您可以重试@ARAVINTHKUMARJ
    • 谢谢.. 但是所有输出都带有'\n'。就像在 chess 之后,我的单元格中有一个 Enter。你能帮我删除它吗?还有一件事:输入:[game] [india] chess 输出:[india] chess ...但现在我什么也没得到(它是空的)。我只想删除搜索字符串。你能帮我解决这个问题吗?
    • if '\n' in temp: temp = temp.split('\n')[0] 从你的代码更改之后..它正在工作。谢谢你!
    猜你喜欢
    • 2023-02-08
    • 2013-12-27
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2014-01-13
    相关资源
    最近更新 更多