Python处理Excel文件(openpyxl库)

一、写入数据:

1. 方式一(推荐):

# 官方文档
# https://openpyxl.readthedocs.io/en/stable/#
# https://openpyxl-chinese-docs.readthedocs.io/zh-cn/latest/tutorial.html#id2


import openpyxl

# 原始数据(包含表头和数据行)
data = [
    ["name", "age", "high"],
    ["hua", 12, 182],
    ["ni", 18, 178]
]

# 1. 创建Excel工作簿对象
excel = openpyxl.Workbook()

# 2. 获取默认活动工作表并重命名(提升可读性)
sheet_active = excel.active
sheet_active.title = "StudentInfo"  # 设置工作表标题

# 3. 使用append()批量写入数据(替代双重循环)
for row_data in data:
    sheet_active.append(row_data)  # 直接追加整行数据

# 4. 显式关闭工作簿并保存文件(良好的资源管理习惯)
excel.save(filename='info.xlsx')


2. 方式二:

# 官方文档
# https://openpyxl.readthedocs.io/en/stable/#
# https://openpyxl-chinese-docs.readthedocs.io/zh-cn/latest/tutorial.html#id2

import openpyxl


data = [
    ["name", "age", 'high'],
    ["huang", 12, 182],
    ["ning", 18, 178]
]
# 创建空的Workbook对象,也就是创建一个excel工作簿
excel = openpyxl.Workbook()
# 获取活跃的表格进行操作 或 创建一个新表进行操作
sheet_active = excel.active
# sheet_new = excel.create_sheet(title="data")  // 创建一个新表
# 默认情况下,新建的Workbook对象对应的Excel 文件中只有一张名字是 'Sheet' 的表
print(excel.sheetnames)
# 写入数据到表格中
for row in range(0, len(data)):
    for col, val in enumerate(data[row]):
        sheet_active.cell(row=row+1, column=col+1,  value=val)
# 保存至文件
excel.save(filename='info.xlsx')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值