报错AttributeError:'Workbook'对象无'write'属性,求Excel均值写入方案
问题描述
需要实现:调用函数后,计算Excel文件中各月份工作表(每个月对应一个独立sheet)的同项数据均值,保存至最后一个名为total的工作表对应位置。例如各月份工作表第1列第2行的"shipping cost"全年均值,要存入total表的第1列第2行。
原函数代码:
def mean_cal(year_num): file = f'year_data/year-{year_num}.xlsx' dataframe = pd.read_excel(f'year_data/year-{year_num}.xlsx', sheet_name=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'total']) month = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] categor = ['incomes', 'costs'] info = [] total = 0 exl = xw.Workbook(file) for categ in categor: for row in range(0, 19): for month_check in month: try: info.append(dataframe[month_check][categ][row]) except ValueError or KeyError: continue for collector in info: total += collector if categ == 'incomes': exl.write(f'F{row}', (total / (len(info)))) else: pass
运行时报错:
Traceback (most recent call last): File "D:\Mahdi\Programming\Projects\Rabin amc\proj_func.py", line 209, in <module> mean_cal(1402) File "D:\Mahdi\Programming\Projects\Rabin amc\proj_func.py", line 106, in mean_cal exl.write(f'F{row}', (total / (len(info)))) ^^^^^^^^^ AttributeError: 'Workbook' object has no attribute 'write'
问题分析与解决方案
1. 报错核心原因
xw.Workbook是pywin32库的对象,本身没有write方法,这是错误的操作方式。另外原代码还存在逻辑缺陷:
info和total未在每次循环时重置,会导致累加数据混乱- 仅处理
incomes列,未实现costs列的均值计算 - 手动循环累加计算均值效率低,容易出错
2. 优化后实现代码
用Pandas完成所有计算与写入操作,高效且避免错误:
import pandas as pd def mean_cal(year_num): file_path = f'year_data/year-{year_num}.xlsx' # 读取所有月份工作表(排除total表) month_sheets = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] dfs = pd.read_excel(file_path, sheet_name=month_sheets) # 合并所有月份数据,按行索引分组计算均值 combined_df = pd.concat([dfs[sheet] for sheet in month_sheets]) mean_df = combined_df.groupby(combined_df.index).mean() # 将均值写入total表,覆盖原有内容 with pd.ExcelWriter(file_path, mode='a', if_sheet_exists='replace') as writer: mean_df.to_excel(writer, sheet_name='total', index=False)
3. 适配特定结构的版本(针对原需求的行/列限制)
如果只需要计算前19行、指定列(incomes/costs)的均值,可使用以下代码:
import pandas as pd def mean_cal(year_num): file_path = f'year_data/year-{year_num}.xlsx' month_sheets = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] dfs = pd.read_excel(file_path, sheet_name=month_sheets) # 筛选目标列与前19行(索引0到18) target_cols = ['incomes', 'costs'] filtered_dfs = [] for sheet in month_sheets: filtered_df = dfs[sheet].loc[0:18, target_cols] filtered_dfs.append(filtered_df) # 计算均值并写入total表 mean_df = pd.concat(filtered_dfs).groupby(level=0).mean() with pd.ExcelWriter(file_path, mode='a', if_sheet_exists='replace') as writer: mean_df.to_excel(writer, sheet_name='total', index=False)
4. 关键说明
- 均值计算逻辑:通过
pd.concat合并所有月份表,按行索引分组求均值,确保每个单元格的均值自动对应total表的相同位置 - 写入方式:
pd.ExcelWriter的mode='a'表示追加模式,if_sheet_exists='replace'会覆盖原有total表,保证每次运行结果最新 - 避免循环错误:摒弃手动累加的方式,用Pandas内置方法彻底解决数据重置、累加混乱的问题
内容的提问来源于stack exchange,提问作者m.mahdi.sangtarash
相关产品推荐
相关产品推荐

