Python 使用 openpyxl 读取 Excel 表格数据并构建用户对象
使用 Python openpyxl 库读取 Excel 表格数据并构建用户对象
首先需要导入 openpyxl 库
import openpyxl
定义 User 类,表示每个用户的信息
class User:
def __init__(self, name, account, balance, is_vip, phone):
self.name = name
self.account = account
self.balance = balance
self.is_vip = is_vip
self.phone = phone
定义 read_excel() 函数,用于读取 Excel 表格数据并构建用户对象
def read_excel():
# 打开表格文件
wb = openpyxl.load_workbook('bank_accounts.xlsx')
# 获取第一个工作表
ws = wb.active
# 定义用户结构体数组
users = []
# 遍历表格中的每一行数据,构造用户结构体并存储到数组中
for row in ws.iter_rows(min_row=2):
user = User(row[0].value, row[1].value, row[2].value, row[3].value, row[4].value)
users.append(user)
return users
使用示例:
# 读取 Excel 表格数据并构建用户对象列表
users = read_excel()
# 打印用户列表
for user in users:
print(f'姓名: {user.name}, 账号: {user.account}, 余额: {user.balance}, 是否 VIP: {user.is_vip}, 手机号码: {user.phone}')
说明:
- 代码中的
bank_accounts.xlsx是 Excel 文件的名称,请根据实际情况修改。 - Excel 表格中的第一行应该是表头,从第二行开始是数据行。
User类中的属性可以根据实际需要进行修改。read_excel()函数的返回值是一个User对象的列表。
代码完整示例:
import openpyxl
class User:
def __init__(self, name, account, balance, is_vip, phone):
self.name = name
self.account = account
self.balance = balance
self.is_vip = is_vip
self.phone = phone
def read_excel():
wb = openpyxl.load_workbook('bank_accounts.xlsx')
ws = wb.active
users = []
for row in ws.iter_rows(min_row=2):
user = User(row[0].value, row[1].value, row[2].value, row[3].value, row[4].value)
users.append(user)
return users
# 读取 Excel 表格数据并构建用户对象列表
users = read_excel()
# 打印用户列表
for user in users:
print(f'姓名: {user.name}, 账号: {user.account}, 余额: {user.balance}, 是否 VIP: {user.is_vip}, 手机号码: {user.phone}')
原文地址: https://www.cveoy.top/t/topic/oI36 著作权归作者所有。请勿转载和采集!