使用 python 和 openpyxl 获取列表并将数据写入新的 xlsx 文件

Take a list and write the data to a new xlsx file using python and openpyxl

所以很多帮助和后来的文档抓耳挠腮:

for row in ws.iter_rows():
        for cell in row:
            if cell.value and isinstance(cell.value, str) and emailRegex.match(cell.value):
                mail = emailRegex.match(cell.value)
                if mail:
                    mail = mail.group(0)
                    customeremails.append(mail)
print(customeremails)

打印命令让我:

['store@xxxx.com', 'xxxx@yahoo.co.in', 'xxxx@gmail.com']

现在我想添加以下内容,尝试将此列表放入从单元格 B2 开始的新 excel 文件中:

                #Adding the below before print(customeremails)
                os.chdir("C:\Python34")  
                wb = Workbook()
                dest_filename = 'trial.xlsx'
                ws1 = wb.active
                ws1.title = sheet
                i = 2
                for i,mail in enumerate(customeremails):
                    ws1.cell(row = i, column = 2).value = mail
                    i = i+1
                    return i
                wb.save(filename = dest_filename)

文件已创建,工作表已重命名。但我只得到列表中的一个电子邮件地址。

这里有 2 个问题:

  • 您正在从循环中返回 i:无用,并且会阻止正确创建文件
  • 您正在使用 enumerate 和 change/initialize i:选择。我会让 enumerate 完成这项工作。

我的建议(向 enumerate 添加了可选参数,因此 i2 开始,行不能是 0):

for i,mail in enumerate(customeremails,2):
    ws1.cell(row = i, column = 2).value = mail
wb.save(filename = dest_filename)