Python Excel实现自动添加编号

2025-03-14 01:50

本文主要是介绍Python Excel实现自动添加编号,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《PythonExcel实现自动添加编号》这篇文章主要为大家详细介绍了如何使用Python在Excel中实现自动添加编号效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...

1、背景介绍

简单的说,就是在Excel中有一列h=会有重复的编号,我们相对这个重复的编号,再次进行编号,使其如有重复就加上-1,-2,-3。。。。。以此类推,将重新生成【新编号】放在其旁边列

2、库的安装

用途安装
openpyxlExcel读取pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/
os获取路径内置库无需安装

3、核心代码

①:编号列的值进行计数

  • 遍历Excel文件的每一行,对编号列的值进行计数。
  • 根据计数值生成新的格式化字符串编号-计数值,并更新到结果编号列。
  • 支持单个文件处理和批量文件处理。
for row_idx in range(2, ws.max_row + 1):
    # Get the 序号 value
    序号_value = ws.cell(row=row_idx, column=序号_index).value

    # Skip if 序号 is None or empty
    if 序号_value is None or str(序号_value).strip() == '':
        continue

    # Convert to string to handle any numeric values
    序号_str = str(序号_value)

    # Initialize count if this is the first occurrence
    if 序号_str not in 序号_counts:
        序号_counts[序号_str] = 0

    # Increment the count
    序号_counts[序号_str] += 1

    # Create the new format: "序号-count"
    new_子账号编号 = f"{序号_str}-{序号_counts[序号_str]}"

    # Update the 子账号编号 cell
    ws.cell(row=row_idx, column=子账号编号_index).value = new_子账号编号

4、完整代码

import os
import openpyxl


def process_subaccount_numbers(file_path, output_path=None):
    # Load the workbook
    print(f"Reading file: {file_path}")
    wb = openpyxl.load_workbook(file_path)
    ws = wb.active

    # Get the headers
    headers = [cell.value for cell in ws[1]]

    # Find the in编程dices of the required columns
    if '编号' not in headers or '结果编号' not in headers:
        print("Error: Required columns '序号' or '结果编号' not found in the Excel file.")
        return

    序号_index = headers.index('编号') + 1  # +1 because openpyxl is 1-indexed
    子账号编号_index = headers.index('结果编号') + 1

    # Create a dictionary to track occurrences of each 序号
    序号_counts = {}

    # Process eacwww.chinasem.cnh row (starting from row 2, skhttp://www.chinasem.cnipping the header)
    for row_idx in range(2, ws.max_row + 1):
        # Get the 序号 value
        序号_value = ws.cell(row=row_idx, column=序号_index).value

        # Skip if 序号 is None or empty
        if 序号_value is None or str(序号_value).strip() == '':
            continue

        # Convert to string to handle any numeric values
        序号_str = str(序号_value)

        # Initialize count if this is the first occurrence
        if 序号_str not in 序号_counts:
            序号_counts[序号_str] = 0

        # Increment the count
        序号_counts[序号_str] += 1

        # Create the new format: "序号-count"
        new_子账号编号 = f"{序号_str}-{序号_counts[序号_str]}"

        # Update the 子账号编号 cell
        ws.cell(row=row_idx, column=子账号编号_index).value = new_子账号编号

    # Determine the output path
    if output_path is None:
        file_name, file_ext = os.path.splitext(file_path)
        output_path = f"{file_name}_processed{file_ext}"

    # Save the modified workbook to a new Excel file
    print(f"Saving processed file to: {output_path}")
    wb.savChina编程e(output_path)
    print("Processing completed successfully!")

    return output_path


def main():
    # Get the data source directory
    data_dir = './数据源/'

    # Find all Excel files in the directory
    excel_files = [f for f in os.listdir(data_dir) if f.endswith('.xlsx') or f.endswith('.xls')]

    if not excel_files:
        print("No Excel files found in the data source directory.")
        return

    # Process each Excel file
    for file_name in excel_files:
        file_path = os.path.join(data_dir, file_name)
        process_subaccount_numbers(file_path)


if __name__ == "__main__":
   puVeDEIi main()

效果如下

Python Excel实现自动添加编号

到此这篇关于python Excel实现自动添加编号的文章就介绍到这了,更多相关Python Excel添加编号内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于Python Excel实现自动添加编号的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153734

相关文章

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部