使用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)
相关推荐
Wellijohn1 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
bufengwangluo2 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶2 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
console.log('npc')2 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
geovindu4 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu5 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
真上帝的左手5 小时前
2. 编程语言-Python-Anaconda
开发语言·python
aifannihao5 小时前
断言从 == 改成 > 0:用 Python 审出 git diff 里的测试降级
git·python·测试·标准库·代码审查
高洁015 小时前
具身智能的人机协作与物理空间安全
人工智能·python·深度学习·机器学习·django