Python Excel实现自动添加编号

 更新时间:2025年03月13日 15:08:34   作者:一晌小贪欢  
这篇文章主要为大家详细介绍了如何使用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 indices 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 each row (starting from row 2, skipping 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.save(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__":
    main()

效果如下

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

相关文章

  • pyhon如何把程序打包为whl

    pyhon如何把程序打包为whl

    这篇文章主要介绍了pyhon如何把程序打包为whl问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Python的轻量级ORM框架peewee使用教程

    Python的轻量级ORM框架peewee使用教程

    这篇文章主要介绍了Python的轻量级ORM框架peewee使用教程,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2021-02-02
  • Python基于DeepSeek大模型的提示词优化方案

    Python基于DeepSeek大模型的提示词优化方案

    以下基于DeepSeek大模型特性及搜索结果的综合分析,结合提示词设计原则、技术原理与优化策略,提供完整Python代码案例及详细解析,需要的朋友可以参考下
    2025-04-04
  • 关于tf.matmul() 和tf.multiply() 的区别说明

    关于tf.matmul() 和tf.multiply() 的区别说明

    这篇文章主要介绍了关于tf.matmul() 和tf.multiply() 的区别说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • 简单有效上手Python3异步asyncio问题

    简单有效上手Python3异步asyncio问题

    这篇文章主要介绍了简单有效上手Python3异步asyncio问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • python密码学库pynacl功能介绍

    python密码学库pynacl功能介绍

    PyNaCI能够提供数字签名、密钥加密、公钥加密、哈希和消息身份验证、基于密码的密钥派生和密码散列功能,这篇文章主要介绍了python密码学库pynacl,感兴趣的朋友一起看看吧
    2022-05-05
  • Python爬虫中Selenium实现文件上传

    Python爬虫中Selenium实现文件上传

    这篇文章主要介绍了Python爬虫中Selenium实现文件上传,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • Python用tkinter实现自定义记事本的方法详解

    Python用tkinter实现自定义记事本的方法详解

    这篇文章主要为大家详细介绍了Python用tkinter实现自定义记事本的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • 搭建 Selenium+Python开发环境详细步骤

    搭建 Selenium+Python开发环境详细步骤

    这篇文章主要介绍了搭建 Selenium+Python开发环境详细步骤的相关资料,需要的朋友可以参考下
    2022-10-10
  • Python3标准库glob文件名模式匹配的问题

    Python3标准库glob文件名模式匹配的问题

    glob的模式规则与re模块使用的正则表达式并不相同。实际上,glob的模式遵循标准UNIX路径扩展规则。只使用几个特殊字符来实现两个不同的通配符和字符区间。这篇文章主要介绍了Python3标准库glob文件名模式匹配的知识,需要的朋友可以参考下
    2020-03-03

最新评论