【Python办公自动化】—Excel中相同编号自动添加-1-2-3...

news/2025/3/15 5:44:19/

目录

  • 专栏导读
  • 1、背景介绍
  • 2、库的安装
  • 3、核心代码
  • 4、完整代码
  • 总结

专栏导读

在这里插入图片描述

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅

  • 🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅

  • 📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅

  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

  • ❤️ 欢迎各位佬关注! ❤️

1、背景介绍

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

2、库的安装

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

3、核心代码

  • ①:编号列的值进行计数

  • 遍历Excel文件的每一行,对编号列的值进行计数。
  • 根据计数值生成新的格式化字符串编号-计数值,并更新到结果编号列。
  • 支持单个文件处理和批量文件处理。
python">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 emptyif 序号_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 occurrenceif 序号_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 子账号编号 cellws.cell(row=row_idx, column=子账号编号_index).value = new_子账号编号

4、完整代码

python">import os
import openpyxldef process_subaccount_numbers(file_path, output_path=None):# Load the workbookprint(f"Reading file: {file_path}")wb = openpyxl.load_workbook(file_path)ws = wb.active# Get the headersheaders = [cell.value for cell in ws[1]]# Find the indices of the required columnsif '编号' 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 emptyif 序号_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 occurrenceif 序号_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 子账号编号 cellws.cell(row=row_idx, column=子账号编号_index).value = new_子账号编号# Determine the output pathif 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 fileprint(f"Saving processed file to: {output_path}")wb.save(output_path)print("Processing completed successfully!")return output_pathdef main():# Get the data source directorydata_dir = './数据源/'# Find all Excel files in the directoryexcel_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 filefor file_name in excel_files:file_path = os.path.join(data_dir, file_name)process_subaccount_numbers(file_path)if __name__ == "__main__":main()

总结

  • 希望对初学者有帮助

  • 致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【一个免费关注】!感谢

  • 求个 🤞 关注 🤞

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 求个 ❤️ 喜欢 ❤️

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 求个 👍 收藏 👍

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏


http://www.ppmy.cn/news/1579238.html

相关文章

python如何获取三个小时之前的时间并输出

python获取三个小时之前的时间的方法: 1、使用“import datetime”导入datetime包 2、用“now()”函数得到的当前时间减去三个小时,输出这个结果就可以了 执行结果如下:

绿色高效运维:分布式光伏监控系统的全生命周期管理

一 碳中和分布式光伏监控系统-概述 碳中和分布式光伏监控系统是针对分散式光伏发电单元(如屋顶光伏、工商业光伏、村级电站等)进行集中化、智能化管理的技术平台,其核心目标是通过实时监测、数据分析与远程控制,实现发电效率大化…

【day13】营销系统:优惠券核销流程

营销系统:优惠券核销流程设计 优惠券核销是营销系统中的核心功能之一,涉及用户使用优惠券、系统验证优惠券有效性、更新优惠券状态等步骤。以下是优惠券核销的详细流程设计: 1. 核销流程概述 用户提交核销请求:用户在支付或结算…

C语言每日一练——day_3(快速上手C语言)

引言 针对初学者,每日练习几个题,快速上手C语言。第三天。(会连续更新) 采用在线OJ的形式 什么是在线OJ? 在线判题系统(英语:Online Judge,缩写OJ)是一种在编程竞赛中用…

微信小程序接入DeepSeek模型(火山方舟),并在视图中流式输出

引言: DeepSeek,作为一款先进的自然语言处理模型,以其强大的文本理解和生成能力著称。它能够处理复杂的文本信息,进行深度推理,并快速给出准确的回应。DeepSeek模型支持流式处理,这意味着它可以边计算边输…

MATLAB代码开发实战:从入门到高效应用

一、MATLAB生态系统的核心优势 (扩展原有内容,增加行业数据) MATLAB在全球工程领域的市场占有率已达67%(2024年IEEE统计),其核心优势体现在: 矩阵运算速度比传统编程快3-5倍包含22个专业工具箱…

Python与Solidity联手:从跨语言智能合约开发到区块链生态跃迁

Python与Solidity联手:从跨语言智能合约开发到区块链生态跃迁 随着区块链技术的高速发展,智能合约正在从“小众极客工具”迅速成为主流应用的技术基石。在这其中,Solidity作为一种主流智能合约开发语言,广泛应用于以太坊等生态。而另一方面,Python以其简单易用、生态丰富…

技术聚焦:Debezium 如何将数据库数据精准注入 Kafka

#作者:任少近 文章目录 第一章 Debezium抽取mysql数据给kafka原理第二章 Debezium 与kafka抽取方法及验证2.1 debezium2.0kafka3.3.1mysql82.2 debezium2.0kafka2.6.1mysql82.3 debezium2.0kafka2.6.1mysql5.7 第一章 Debezium抽取mysql数据给kafka原理 debezium的…