写入
代码
from openpyxl import Workbook
# 创建一个Workbook对象
wb = Workbook()
# 获取当前活跃的sheet,默认是第一个sheet
ws = wb.active
ws['A1'] = '用户名'
ws['B1'] = '年龄 '
ws['C1'].value = '男/女'
row1 = ['小黄', "20", '女']
row2 = ['小绿', "13", '男']
ws.append(row1)
ws.append(row2)
wb.save("a.xlsx")
结果
读取
代码
from openpyxl import load_workbook
wb = load_workbook("a.xlsx")
# 获取所有表格(worksheet)的名字
sheets = wb.sheetnames
# 第一个表格的名称
sheet_first = sheets[0]
# 获取特定的worksheet
ws = wb[sheet_first]
# 获取表格所有行和列,两者都是可迭代的
rows = ws.rows
content = []
# 迭代所有的行
for row in rows:
line = [col.value for col in row]
content.append(line)
print(content)
结果