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中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合