使用 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 "复制完成。"
相关推荐
醇醛酸醚酮酯3 分钟前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
前端付豪7 分钟前
17、自动化才是正义:用 Python 接管你的日常琐事
后端·python
jioulongzi8 分钟前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
破无差39 分钟前
python实现简单的地图绘制与标记20250705
python
向阳@向远方40 分钟前
第二章 简单程序设计
开发语言·c++·算法
喜欢吃豆1 小时前
目前最火的agent方向-A2A快速实战构建(二): AutoGen模型集成指南:从OpenAI到本地部署的全场景LLM解决方案
后端·python·深度学习·flask·大模型
Mr_Xuhhh1 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华1 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
好开心啊没烦恼1 小时前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析
liulilittle1 小时前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信