如何用openpyxl向Excel指定工作表添加数据?
解决openpyxl指定Excel工作表写入数据的问题
问题背景
需向Registry.xlsx的Student Profile和Student Grades工作表写入/更新数据,原代码依赖file.active操作默认激活工作表,导致第二次写入覆盖Student Profile数据;尝试错误语法调用指定工作表均报错,且项目要求完全自动化,不能手动操作Excel。
错误原因
file.active会返回工作簿中当前激活的工作表(默认是第一个创建的工作表),而非目标工作表,导致写入错位。- 错误语法分析:
sheet = file["Student Grades"].active:file["Student Grades"]本身就是工作表对象,不存在active属性。sheet["Student Grades", "A1"] = "ID No.":该语法不支持跨工作表指定单元格,必须先获取目标工作表对象再操作。
正确实现代码
初始化工作表并写入表头
from openpyxl import load_workbook # 加载现有工作簿 file = load_workbook("Registry.xlsx") # 确保Student Profile工作表存在并写入数据 if "Student Profile" not in file.sheetnames: profile_sheet = file.create_sheet("Student Profile") else: profile_sheet = file["Student Profile"] profile_sheet["A1"] = "ID No.:" profile_sheet["B1"] = "Last Name:" profile_sheet["C1"] = "First Name:" profile_sheet["D1"] = "Middle Name:" profile_sheet["E1"] = "Sex:" profile_sheet["F1"] = "Date of Birth:" # 确保Student Grades工作表存在并写入数据 if "Student Grades" not in file.sheetnames: grades_sheet = file.create_sheet("Student Grades") else: grades_sheet = file["Student Grades"] grades_sheet["A1"] = "ID No:" grades_sheet["B1"] = "Math" grades_sheet["C1"] = "Science:" grades_sheet["D1"] = "English" # 保存更改 file.save("Registry.xlsx")
后续频繁更新指定工作表
from openpyxl import load_workbook file = load_workbook("Registry.xlsx") # 直接通过工作表名称获取目标对象 grades_sheet = file["Student Grades"] # 更新单元格数据 grades_sheet["A2"] = "S001" grades_sheet["B2"] = 95 grades_sheet["C2"] = 92 grades_sheet["D2"] = 88 # 同理操作Student Profile profile_sheet = file["Student Profile"] profile_sheet["A2"] = "S001" profile_sheet["B2"] = "Smith" profile_sheet["C2"] = "John" file.save("Registry.xlsx")
注意事项
- 操作完成后必须调用
file.save()才能将更改写入文件。 - 确保操作时Excel文件未被其他程序占用,否则会抛出权限错误。
- 若工作簿不存在,
load_workbook会报错,需提前创建空工作簿或添加判断逻辑处理。
内容的提问来源于stack exchange,提问作者dioscuri
相关产品推荐
相关产品推荐

