要使用Python拆分表格并通过邮件发送,你可以按照以下步骤操作:
拆分表格
使用`pandas`库读取Excel文件,并根据某一列(例如“店铺”)的不同值拆分成多个工作表。
```python
import pandas as pd
import xlsxwriter
读取Excel文件
data = pd.read_excel('path_to_your_file.xlsx', encoding='gbk')
获取唯一值列表
area_list = list(set(data['店铺']))
writer = pd.ExcelWriter('path_to_output_file.xlsx', engine='xlsxwriter')
将原始数据写入总表
data.to_excel(writer, sheet_name='总表', index=False)
遍历唯一值列表,将数据写入新的工作表
for j in area_list:
df = data[data['店铺'] == j]
df.to_excel(writer, sheet_name=j, index=False)
保存Excel文件
writer.save()
发送邮件
使用`smtplib`库发送邮件,并将拆分后的Excel文件作为附件发送给收件人。
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
配置SMTP服务器信息
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'
from_email = ''
to_emails = ['', '']
创建邮件对象
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = ', '.join(to_emails)
msg['Subject'] = '拆分后的表格'
添加邮件正文
body = '您好,这是拆分后的表格文件,请查收。'
msg.attach(MIMEText(body, 'plain'))
添加附件
for sheet_name in area_list:
attachment_path = f'path_to_output_file.xlsxSheet{sheet_name}'
with open(attachment_path, 'rb') as attachment_file:
attachment = MIMEApplication(attachment_file.read(), _subtype='xlsx')
attachment.add_header('Content-Disposition', f'attachment; filename="Sheet{sheet_name}.xlsx"')
msg.attach(attachment)
发送邮件
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(from_email, to_emails, msg.as_string())
server.quit()
请确保替换代码中的`path_to_your_file.xlsx`、`path_to_output_file.xlsx`、`smtp.example.com`、`your_username`、`your_password`、``和``等占位符为实际的文件路径和邮箱信息。
完成上述步骤后,拆分后的Excel文件将作为附件通过邮件发送给指定的收件人