![](/img/trans.png)
[英]how can I make Xlsxwriter by default activate the headings in an Excel sheet?
[英]How can I make python find this word on an excel sheet?
我試圖讓 python 在 excel 表中找到特定的單詞。 盡管如此,盡管到處搜索如何做到這一點,我還是找不到答案。
import re
with open('ptry.xlsx') as aa:
for line in aa:
match = re.search(r'abc', line)
if match:
print("yes")
else:
print ("no")
這段代碼給了我以下結果:
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
重新關閉
盡管如此,我期待一個簡單的“是”,因為“abc”這個詞在我的 excel 表上。
如果您使用的是 Excel,我可以建議使用 Openpyxl 嗎?
import os
#Change to the dir of your spreadsheet
from openpyxl import load_workbook
wb = load_workbook(filename='Insert your file here', data_only=True)
#data_only=False by default
#If you want to see data instead of formulas, set data_only=True
ws = wb['Sheet1'] #Or whatever your sheet name is
for num_row in range (1, ws.max_row):
if ws['A{}'.format(num_row)].value=='abc':
print ('yes')
else:
print ('no')
#You can also use ws.max_column
這應該讓您大致了解如何使用 openpyxl。 如果您還有其他問題,請告訴我。
可能有更好的方法,但這可以解決問題。 在下面的代碼中,以文本格式創建 excel 文件的副本,然后創建一個列表並檢查文件中的“單詞”。
import pandas as pd
df = pd.read_excel("ptry.xlsx")
df.to_csv("ptry.txt")
filex = open("ptry.txt", "r")
filex_string = filex.read()
filex_list = filex_string.split(",")
if "word" in filex_list:
print("True")
else:
print("false")
import openpyxl
excel_var = openpyxl.load_workbook('excelname.xlsx')
sheet = excel_name.get_sheet_by_name('sheetname')
for row in sheet.iter_rows(min_row=minr, min_col=5, max_col=11, max_row=maxr):
match = re.search(r'abc', line)
if match:
print("yes")
else:
print("no")
請注意,您應該限制 for 循環中的行和列有一個 vars minr 和 maxr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.