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实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

python获取网页表格的多种方法汇总

《python获取网页表格的多种方法汇总》我们在网页上看到很多的表格,如果要获取里面的数据或者转化成其他格式,就需要将表格获取下来并进行整理,在Python中,获取网页表格的方法有多种,下面就跟随小编... 目录1. 使用Pandas的read_html2. 使用BeautifulSoup和pandas3.

PyQt6/PySide6中QTableView类的实现

《PyQt6/PySide6中QTableView类的实现》本文主要介绍了PyQt6/PySide6中QTableView类的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学... 目录1. 基本概念2. 创建 QTableView 实例3. QTableView 的常用属性和方法

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰

PyQt6/PySide6中QTreeView类的实现

《PyQt6/PySide6中QTreeView类的实现》QTreeView是PyQt6或PySide6库中用于显示分层数据的控件,本文主要介绍了PyQt6/PySide6中QTreeView类的实现... 目录1. 基本概念2. 创建 QTreeView 实例3. QTreeView 的常用属性和方法属性

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数

Golang HashMap实现原理解析

《GolangHashMap实现原理解析》HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持高效的插入、查找和删除操作,:本文主要介绍GolangH... 目录HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持

Pandas使用AdaBoost进行分类的实现

《Pandas使用AdaBoost进行分类的实现》Pandas和AdaBoost分类算法,可以高效地进行数据预处理和分类任务,本文主要介绍了Pandas使用AdaBoost进行分类的实现,具有一定的参... 目录什么是 AdaBoost?使用 AdaBoost 的步骤安装必要的库步骤一:数据准备步骤二:模型