新猿木子李:0基础学python培训教程 Python操作Excel之读取数据

#### Python操作Excel之读取数据

```python

'''需要安装模块: pip install  xlrd'''

# 导入 xlrd 库

import xlrd

# 打开刚才我们写入的 test_w.xls 文件

wb = xlrd.open_workbook("test_w.xls")

# 获取并打印 sheet 数量

print("sheet 数量:", wb.nsheets)

# 获取并打印 sheet 名称

print("sheet 名称:", wb.sheet_names())

# 根据 sheet 索引获取内容

sh1 = wb.sheet_by_index(0)

# 或者

# 也可根据 sheet 名称获取内容

# sh = wb.sheet_by_name('成绩')

# 获取并打印该 sheet 行数和列数

print(u"sheet %s 共 %d 行 %d 列" % (sh1.name, sh1.nrows, sh1.ncols))

# 获取并打印某个单元格的值

print("第一行第二列的值为:", sh1.cell_value(0, 1))

# 获取整行或整列的值

rows = sh1.row_values(0)  # 获取第一行内容

cols = sh1.col_values(1)  # 获取第二列内容

# 打印获取的行列值

print("第一行的值为:", rows)

print("第二列的值为:", cols)

# 获取单元格内容的数据类型

print("第二行第一列的值类型为:", sh1.cell(1, 0).ctype)

# 遍历所有表单内容

for sh in wb.sheets():

    for r in range(sh.nrows):

        # 输出指定行

        print(sh.row(r))

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你可以使用Python中的openpyxl库来读取Excel文件,使用smtplib库来发送邮件。以下是一个简单的示例代码: ```python import openpyxl import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # 读取Excel文件 wb = openpyxl.load_workbook('emails.xlsx') sheet = wb.active # 邮件信息 sender_email = 'your_email@example.com' sender_password = 'your_password' subject = '邮件主题' body = '邮件正文' # 登录邮箱服务器 smtp_server = 'smtp.example.com' smtp_port = 587 smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.starttls() smtp.login(sender_email, sender_password) # 发送邮件 for row in sheet.iter_rows(min_row=2, values_only=True): recipient_email = row[0] recipient_name = row[1] message = MIMEMultipart() message['From'] = sender_email message['To'] = recipient_email message['Subject'] = subject # 正文 message.attach(MIMEText(f'{recipient_name},{body}', 'plain')) # 附件 with open('attachment.pdf', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='pdf') attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf') message.attach(attachment) smtp.sendmail(sender_email, recipient_email, message.as_string()) # 关闭邮箱服务器连接 smtp.quit() ``` 以上代码将Excel文件中第一列作为接收人的邮件地址,第二列作为接收人的姓名。邮件正文中包含接收人的姓名,附件为一个名为`attachment.pdf`的PDF文件。你需要将`your_email@example.com`和`your_password`替换为你自己的邮箱地址和密码,将`smtp.example.com`替换为你的邮箱提供商的SMTP服务器地址,将`587`替换为SMTP服务器的端口号。同时,你还需要将`emails.xlsx`和`attachment.pdf`替换为你自己的Excel文件和附件文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值