使用openpyxl实现GUI提交数据追加至Excel时遇AttributeError求助
问题:使用openpyxl追加Excel数据时出现AttributeError错误
我在GUI界面点击提交按钮时,需要将用户输入的所有数据写入Excel文件,每条新记录自动追加到最新记录下方。目前已成功实现表头写入,但使用openpyxl库时出现报错:AttributeError: 'NoneType' object has no attribute 'append'。
我的代码片段
filepath = "C:\\xxxx\\xxxx\\xxxx\\xxxx\\xxxx\\Collecting Data.xlsx" if not os.path.exists(filepath): xlsx_open = openpyxl.Xlsx_openxlsx_open() sheet = xlsx_open.active table_headings = ["Card Type", "Staff Number", "Staff Name", "Staff Title", "Department", "Safety Function", "Safety Standards", "Brief Description of the Incident"] sheet.append(table_headings) xlsx_open.save(filepath) xlsx_open = openpyxl.load_xlsx_open(filepath) sheet = xlsx_open.active sheet.append([staff_name_entry, staff_id_dropdown, staff_title_entry, department_entry, card_type_dropdown, safety_function_dropdown, safety_standard_dropdown, manualy_text_entry]) xlsx_open.save(filepath) window.mainloop()
报错信息
Error: submit_form sheet.append([CardTypeDropdown, StaffIdDropdown, StaffNameEntry, StaffTitleEntry, DepartmentEntry, ^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'append'
解决方法
错误原因分析
- 调用了不存在的openpyxl API:
Xlsx_openxlsx_open()和load_xlsx_open()不是openpyxl的标准方法,调用它们会返回None,导致后续sheet = xlsx_open.active得到的也是None,触发AttributeError。 - 直接传入控件对象而非输入值:代码中直接把GUI控件(如
staff_name_entry)传入sheet.append(),正确做法应该是获取控件的实际输入值(比如Tkinter控件用.get()方法)。 - 缺失文件存在时的处理逻辑:原代码只处理了文件不存在的情况,文件已存在时无法追加数据。
修正后的代码
import os import openpyxl # 假设此处已定义所有GUI控件(如Tkinter的Entry、Dropdown等) # 示例: # import tkinter as tk # window = tk.Tk() # staff_name_entry = tk.Entry(window) # 其他控件同理 def submit_form(): filepath = "C:\\xxxx\\xxxx\\xxxx\\xxxx\\xxxx\\Collecting Data.xlsx" table_headings = ["Card Type", "Staff Number", "Staff Name", "Staff Title", "Department", "Safety Function", "Safety Standards", "Brief Description of the Incident"] # 正确获取用户输入的实际值 record_data = [ card_type_dropdown.get(), staff_id_dropdown.get(), staff_name_entry.get(), staff_title_entry.get(), department_entry.get(), safety_function_dropdown.get(), safety_standard_dropdown.get(), manualy_text_entry.get() ] if not os.path.exists(filepath): # 创建新工作簿(标准API) wb = openpyxl.Workbook() sheet = wb.active sheet.append(table_headings) # 写入表头 sheet.append(record_data) # 写入第一条记录 wb.save(filepath) else: # 加载现有工作簿(标准API) wb = openpyxl.load_workbook(filepath) sheet = wb.active sheet.append(record_data) # 追加新记录 wb.save(filepath) # window.mainloop()
关键说明
- 使用openpyxl官方标准方法:
openpyxl.Workbook()创建新工作簿,openpyxl.load_workbook()加载现有文件,避免返回None对象。 - 所有GUI控件必须调用
.get()方法获取用户输入的实际内容,而非直接传入控件对象。 - 拆分文件存在/不存在的逻辑,确保两种场景下都能正确追加数据。
内容的提问来源于stack exchange,提问作者The Clueless Engineer
相关产品推荐
相关产品推荐

