使用Python和Pandas将Excel文件中的每个Sheet保存为独立文件

复制代码
import pandas as pd
import os
from pathlib import Path

# 读取原始Excel文件
excel_file = pd.ExcelFile(r'C:\Users\wangkejun\Desktop\id.xlsx')

# 获取Excel文件名(不带扩展名)
file_name = Path(r'C:\Users\wangkejun\Desktop\id.xlsx').stem

# 创建保存文件的目录
output_dir = r'C:\Users\wangkejun\Desktop'
os.makedirs(output_dir, exist_ok=True)

# 遍历每个sheet并保存为独立的Excel文件
for sheet_name in excel_file.sheet_names:
    # 读取当前sheet的数据
    df = excel_file.parse(sheet_name)
    
    # 构造保存文件的路径
    output_file = os.path.join(output_dir, f'{file_name}_{sheet_name}.xlsx')
    
    # 将当前sheet保存为独立的Excel文件
    df.to_excel(output_file, index=False)
  1. 获取Excel文件的文件名(不带扩展名):

    • file_name = Path(r'C:\Users\wangkejun\Desktop\id.xlsx').stem
  2. 创建保存文件的目录:

    • output_dir = r'C:\Users\wangkejun\Desktop'
    • os.makedirs(output_dir, exist_ok=True)
  3. 遍历每个sheet并保存为独立的Excel文件:

    • 使用for循环遍历excel_file.sheet_names,即所有sheet的名称。
    • 在循环中,读取当前sheet的数据:
      • df = excel_file.parse(sheet_name)
    • 构造保存文件的路径:
      • output_file = os.path.join(output_dir, f'{file_name}_{sheet_name}.xlsx')
    • 将当前sheet保存为独立的Excel文件:
      • df.to_excel(output_file, index=False)
相关推荐
you鬰4 分钟前
datawhale--llm-algo-leetcode5️⃣
python·datawhale
λqaq725 分钟前
MySQL 数据库基础(2)约束、用户权限、远程连接、外键与 TCP/UDP 理解
linux·数据库·python·tcp/ip·mysql
人工干智能28 分钟前
科普:pandas 时间偏移别名:ts.resample(“5Min“).sum()
python·pandas
开源量化GO37 分钟前
最新AI辅助量化表达:先理清规则,再按需求选工具
人工智能·python
Zane199444 分钟前
为什么 del 一个对象有时立刻消失,有时却纹丝不动?一文讲透引用计数与垃圾回收
后端·python
yichudu1 小时前
Python 装饰器 decorator
开发语言·python
一晌小贪欢1 小时前
Python办公14:批量解压文件夹内的所有 ZIP/RAR 并自动分类
开发语言·python·excel·数据可视化·python办公
Python 实战手记1 小时前
企业微信主体变更公证书办理全解析:适用场景、材料规范、踩坑点与Python信息校验脚本
开发语言·python·企业微信
郝学胜_神的一滴1 小时前
Effective Python 条款 2:遵循 PEP 8 编码风格,写出高质量 Python 代码
python·算法
郝学胜-神的一滴1 小时前
Effective Python 条款 1:确认你正在使用的 Python 版本
开发语言·数据结构·python·程序人生·算法