You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按customer字段拆分数据存为独立Excel文件报错解决

问题描述

现有如下测试DataFrame:

import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(100)
cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                   'customer': rng.choice(list('ACD'),size=(5)),
                   'region': rng.choice(list('PQRS'),size=(5)),
                   'dumeel': rng.choice(list('QWER'),size=(5)),
                   'dumma': rng.choice((1234),size=(5)),
                   'target': rng.choice([0,1],size=(5))
})

需要实现两项操作:

  • 基于customer字段对数据集进行筛选拆分
  • 将每个拆分得到的数据子集存储为独立的.xlsx文件,文件名使用对应的customer值命名(数据中共有A、C、D三个唯一customer值,最终应生成3个Excel文件)

最初编写的实现代码如下:

for cust, v in cdf.groupby(['customer']):
    writer = pd.ExcelWriter(f"{cust}.xlsx", engine='xlsxwriter')
    v.to_excel(writer, sheet_name=f'{cust}')
    writer.close()

代码运行后虽然生成了对应文件,但打开时弹出报错:

Excel cannot open the file A.xlsx because the file format or extension is not valid. Verify that file has been corrupted and that file extension matches the format of the file

需要找到规避该报错的方法,实现按customer拆分数据后,每个客户对应的数据存储为独立Excel文件,且文件名、内置工作表名均为对应的客户名称。

解决方案

这个报错是因为手动调用close()方法时,容易出现文件写入流未正常释放、内容未完全写入就被截断的问题,最终生成的文件是损坏的。直接使用with上下文管理器操作ExcelWriter即可,它会在写入操作完成后自动回收资源、完整关闭文件,不需要手动调用close()方法。

修正后的可运行代码如下:

# 按customer字段分组遍历
for cust, group_df in cdf.groupby('customer'):
    with pd.ExcelWriter(f"{cust}.xlsx", engine='xlsxwriter') as writer:
        group_df.to_excel(writer, sheet_name=str(cust), index=False)

如果运行环境未安装xlsxwriter依赖,可先执行安装命令:
pip install xlsxwriter

不想额外安装依赖的话,也可以替换为pandas默认适配的openpyxl引擎,实现效果完全一致:

for cust, group_df in cdf.groupby('customer'):
    with pd.ExcelWriter(f"{cust}.xlsx", engine='openpyxl') as writer:
        group_df.to_excel(writer, sheet_name=str(cust), index=False)

代码说明:

  • 传入index=False是为了避免将pandas默认的行索引写入Excel,输出内容更整洁
  • 对分组值cust做str()类型转换,可兼容分组值为非字符串类型的场景,避免工作表名传参类型报错
  • 代码运行后会生成A.xlsx、C.xlsx、D.xlsx三个文件,文件名、文件内置工作表名均与对应客户名称一致,可正常打开无报错。

内容的提问来源于stack exchange,提问作者The Great

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 20:24:10