我在下面的代码中找到了Excel工作表的第J列中的非空值。它使用它做了一些事情,包括在K列中获取值的电子邮件地址。然后它使用smtp通过电子邮件发送成员。
我想要的是从Python列表中获取该人的电子邮件,该列表可以在代码的开头声明。我无法弄清楚如何在列表中的工作表中找到列J中的匹配名称,然后从列表中获取生成的电子邮件地址。
请原谅任何可怕的语法......这是我对一个主要python项目的第一次尝试。
memlist = {'John Frank':'email@email.com',
'Liz Poe':'email2@email.com'}
try:
for i in os.listdir(os.getcwd()):
if i.endswith(".xlsx") or i.endswith(".xls"):
workbook = load_workbook(i, data_only=True)
ws = workbook.get_sheet_by_name(wsinput)
cell_range = ws['j3':'j7']
for row in cell_range: # This is iterating through rows 1-7
#for matching names in memlist
for cell in row: # This iterates through the columns(cells) in that row
value = cell.value
if cell.value:
if cell.offset(row=0, column =-9).value.date() == (datetime.now().date() + timedelta(days=7)):
#print(cell.value)
email = cell.offset(row=0, column=1).value
name = cell.value.split(',',1)[0]
答案 0 :(得分:0)
这是我尝试回答。
memlist
不是list
,而是dict
,因为它包含key : value
对。
如果您想检查dict
中是否存在某个密钥,可以使用dict.has_key(key)
方法。
在memlist
中,名称为key
,相应的电子邮件为value
。
在您的代码中,您可以这样做:
if memlist.has_key(cell.value): # For Python 2
if ... # From your code
email = memlist[cell.value]
如果你正在使用Python 3,你可以搜索这样的密钥:
if cell.value in memlist: # For Python 3
看看这是否适合你,因为我无法完全理解你的问题。
答案 1 :(得分:0)
Shubham, 我用你的一部分回答来找到我自己的答案。我只使用了另一个for / in语句和后续的if语句而不是has_key方法。
然而,我担心的是,对于这些多个用户和代码,代码需要很长时间才能运行,而且可能不是最有效/最佳的。但那是值得的另一天。
try:
for i in os.listdir(os.getcwd()):
if i.endswith(".xlsx") or i.endswith(".xls"):
workbook = load_workbook(i, data_only=True)
ws = workbook.get_sheet_by_name(wsinput)
cell_range = ws['j3':'j7']
for row in cell_range: # This is iterating through rows 1-7
for cell in row: # This iterates through the columns(cells) in that row
value = cell.value
if cell.value:
if cell.offset(row=0, column =-9).value.date() == (datetime.now().date() + timedelta(days=7)):
for name, email in memlist.items():
if cell.value == name:
#send the email