使用 python 拆分 excel 文件

文章目录

1、安装虚拟环境(在特定文件夹内)

复制代码
# 头两步一台机器只执行一次即可
brew install python3
xcode-select --install

# 虚拟环境
python3 -m venv my_pandas_venv
source my_pandas_venv/bin/activate
pip install pandas
pip install openpyxl

2、脚本 split.sh

拆成 2 个

复制代码
#!/bin/bash

# 检查 Python3 和 pandas 库是否已安装
if ! command -v python3 &> /dev/null; then
    echo "需要安装 Python3。"
    exit 1
fi

if ! python3 -c "import pandas" &> /dev/null; then
    echo "需要安装 pandas 库(对于Python3)。"
    exit 1
fi

# 输入参数验证
if [ $# -ne 1 ]; then
    echo "请提供要拆分的 Excel 文件的路径作为参数。"
    exit 1
fi

input_file="$1"

# 使用 pandas 读取 Excel 文件
python3 << EOF
import pandas as pd

# 读取 Excel 文件
try:
    df = pd.read_excel("$input_file")
except Exception as e:
    print("读取 Excel 文件时发生错误:", str(e))
    exit(1)

# 获取总行数
total_rows = len(df)

# 计算每个文件应包含的行数(向上取整)
rows_per_file = -(-total_rows // 2)

# 拆分并保存到两个文件
file1 = df[:rows_per_file]
file2 = df[rows_per_file:]
try:
    file1.to_excel("output1.xlsx", index=False)
    file2.to_excel("output2.xlsx", index=False)
except Exception as e:
    print("保存拆分文件时发生错误:", str(e))
    exit(1)

print("拆分完成。")
EOF

拆成 10 个

复制代码
#!/bin/bash

# 检查 Python3 和 pandas 库是否已安装
if ! command -v python3 &> /dev/null; then
    echo "需要安装 Python3。"
    exit 1
fi

if ! python3 -c "import pandas" &> /dev/null; then
    echo "需要安装 pandas 库(对于Python3)。"
    exit 1
fi

# 输入参数验证
if [ $# -ne 1 ]; then
    echo "请提供要拆分的 Excel 文件的路径作为参数。"
    exit 1
fi

input_file="$1"

# 使用 pandas 读取 Excel 文件
python3 << EOF
import pandas as pd
import math

# 读取 Excel 文件
try:
    df = pd.read_excel("$input_file")
except Exception as e:
    print("读取 Excel 文件时发生错误:", str(e))
    exit(1)

# 获取总行数
total_rows = len(df)

# 计算每个文件应包含的行数(向上取整)
rows_per_file = math.ceil(total_rows / 10)

# 拆分成多个文件
for i in range(10):
    start_row = i * rows_per_file
    end_row = (i + 1) * rows_per_file
    file = df[start_row:end_row]
    try:
        file.to_excel(f"output{i+1}.xlsx", index=False)
    except Exception as e:
        print(f"保存拆分文件 {i+1} 时发生错误:", str(e))
        exit(1)

print("拆分完成。")
EOF

把拆分的子文件直接复制到指定子文件夹(保持子文件和原始 excel 文件同名)

复制代码
#!/bin/bash

# 检查 Python3 和 pandas 库是否已安装
if ! command -v python3 &> /dev/null; then
    echo "需要安装 Python3。"
    exit 1
fi

if ! python3 -c "import pandas" &> /dev/null; then
    echo "需要安装 pandas 库(对于Python3)。"
    exit 1
fi

input_file="$1"
output_folder="$2"

# 使用 pandas 读取 Excel 文件并拆分
python3 << EOF
import pandas as pd
import math
import os

# 读取 Excel 文件
try:
    df = pd.read_excel("$input_file")
except Exception as e:
    print("读取 Excel 文件时发生错误:", str(e))
    exit(1)

# 获取总行数
total_rows = len(df)

# 计算每个文件应包含的行数(向上取整)
rows_per_file = math.ceil(total_rows / 10)

# 拆分成多个文件
for i in range(10):
    start_row = i * rows_per_file
    end_row = (i + 1) * rows_per_file
    file = df[start_row:end_row]
    
    # 子文件夹路径
    subfolder = f"subtask{i+1}/prepareInfo"
    target_subfolder = os.path.join(subfolder)

    # 保存拆分文件到子文件夹
    output_file = os.path.join(target_subfolder, f"$input_file")
    try:
        file.to_excel(output_file, index=False)
    except Exception as e:
        print(f"保存拆分文件 {i+1} 时发生错误:", str(e))
        exit(1)

print("拆分完成。")
EOF

3、运行脚本(在特定文件夹内)

复制代码
chmod +x split.sh
source my_pandas_venv/bin/activate
(my_pandas_venv) ➜  excelSplit ./split.sh split.xlsx  

4、结果


拆分后的文件

附录

复制文件夹

复制代码
#!/bin/bash

source_dir="task"  # 源目录名
target_prefix="subtask"  # 目标目录名前缀
num_copies=10  # 复制的次数

# 创建目标目录
mkdir -p "$target_prefix"

# 复制目录
for ((i=1; i<=num_copies; i++))
do
    target_dir="${target_prefix}${i}"
    cp -r "$source_dir" "$target_dir"
done

echo "复制完成。"
相关推荐
CodeSheep程序羊4 小时前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
独好紫罗兰4 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
机器学习之心HML4 小时前
多光伏电站功率预测新思路:当GCN遇见LSTM,解锁时空预测密码,python代码
人工智能·python·lstm
2401_841495644 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
王大傻09284 小时前
python 读取文件可以使用open函数的 r 模式
python
I'mChloe4 小时前
PTO-ISA 深度解析:PyPTO 范式生成的底层指令集与 NPU 算子执行的硬件映射
c语言·开发语言
JarryStudy4 小时前
HCCL与PyTorch集成 hccl_comm.cpp DDP后端注册全流程
人工智能·pytorch·python·cann
编程小白20264 小时前
从 C++ 基础到效率翻倍:Qt 开发环境搭建与Windows 神级快捷键指南
开发语言·c++·windows·qt·学习
woshikejiaih4 小时前
**播客听书与有声书区别解析2026指南,适配不同场景的音频
大数据·人工智能·python·音视频
深蓝海拓4 小时前
PySide6,QCoreApplication::aboutToQuit与QtQore.qAddPostRoutine:退出前后的清理工作
笔记·python·qt·学习·pyqt