使用 python 拆分 excel 文件

1、安装环境

brew install python3
python3 -m venv my_pandas_venv
source my_pandas_venv/bin/activate
pip install pandas

2、脚本 split.sh

#!/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

3、运行脚本

chmod +x split.sh
./split.sh demo.xlsx

相关推荐

  1. 使用 python excel 文件

    2024-03-27 02:48:02       18 阅读
  2. VBA Excel中的各sheet为文件

    2024-03-27 02:48:02       13 阅读
  3. pythonexcel第七节 工作簿

    2024-03-27 02:48:02       14 阅读
  4. Excel使用pandas单元格扩展

    2024-03-27 02:48:02       38 阅读
  5. 使用pandasexcel单元格

    2024-03-27 02:48:02       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-27 02:48:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-27 02:48:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-27 02:48:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-27 02:48:02       20 阅读

热门阅读

  1. 电子商务类网站搭建需要注意的几点。

    2024-03-27 02:48:02       20 阅读
  2. springboot如何通过注解优雅实现接口多版本管理

    2024-03-27 02:48:02       18 阅读
  3. 数据结构面试常见问题

    2024-03-27 02:48:02       18 阅读
  4. 09 React使用dayjs

    2024-03-27 02:48:02       20 阅读
  5. Python之数据分析二

    2024-03-27 02:48:02       17 阅读
  6. GB 16807-2009 防火膨胀密封件检测

    2024-03-27 02:48:02       17 阅读
  7. HDOJ 2078

    2024-03-27 02:48:02       16 阅读
  8. UR5 机器人 URDF 代码阅读

    2024-03-27 02:48:02       17 阅读