Python Excel實現(xiàn)自動添加編號
1、背景介紹
簡單的說,就是在Excel中有一列h=會有重復(fù)的編號,我們相對這個重復(fù)的編號,再次進行編號,使其如有重復(fù)就加上-1,-2,-3。。。。。以此類推,將重新生成【新編號】放在其旁邊列
2、庫的安裝
| 庫 | 用途 | 安裝 |
|---|---|---|
| openpyxl | Excel讀取 | pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| os | 獲取路徑 | 內(nèi)置庫無需安裝 |
3、核心代碼
①:編號列的值進行計數(shù)
- 遍歷Excel文件的每一行,對編號列的值進行計數(shù)。
- 根據(jù)計數(shù)值生成新的格式化字符串編號-計數(shù)值,并更新到結(jié)果編號列。
- 支持單個文件處理和批量文件處理。
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 '結(jié)果編號' not in headers:
print("Error: Required columns '序號' or '結(jié)果編號' not found in the Excel file.")
return
序號_index = headers.index('編號') + 1 # +1 because openpyxl is 1-indexed
子賬號編號_index = headers.index('結(jié)果編號') + 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 = './數(shù)據(jù)源/'
# 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()效果如下

到此這篇關(guān)于Python Excel實現(xiàn)自動添加編號的文章就介紹到這了,更多相關(guān)Python Excel添加編號內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基于DeepSeek大模型的提示詞優(yōu)化方案
以下基于DeepSeek大模型特性及搜索結(jié)果的綜合分析,結(jié)合提示詞設(shè)計原則、技術(shù)原理與優(yōu)化策略,提供完整Python代碼案例及詳細解析,需要的朋友可以參考下2025-04-04
關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說明
這篇文章主要介紹了關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python用tkinter實現(xiàn)自定義記事本的方法詳解
這篇文章主要為大家詳細介紹了Python用tkinter實現(xiàn)自定義記事本的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03
搭建?Selenium+Python開發(fā)環(huán)境詳細步驟
這篇文章主要介紹了搭建?Selenium+Python開發(fā)環(huán)境詳細步驟的相關(guān)資料,需要的朋友可以參考下2022-10-10

