Python Excel實(shí)現(xiàn)自動(dòng)添加編號(hào)
1、背景介紹
簡(jiǎn)單的說,就是在Excel中有一列h=會(huì)有重復(fù)的編號(hào),我們相對(duì)這個(gè)重復(fù)的編號(hào),再次進(jìn)行編號(hào),使其如有重復(fù)就加上-1,-2,-3。。。。。以此類推,將重新生成【新編號(hào)】放在其旁邊列
2、庫(kù)的安裝
| 庫(kù) | 用途 | 安裝 |
|---|---|---|
| openpyxl | Excel讀取 | pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| os | 獲取路徑 | 內(nèi)置庫(kù)無需安裝 |
3、核心代碼
①:編號(hào)列的值進(jìn)行計(jì)數(shù)
- 遍歷Excel文件的每一行,對(duì)編號(hào)列的值進(jìn)行計(jì)數(shù)。
- 根據(jù)計(jì)數(shù)值生成新的格式化字符串編號(hào)-計(jì)數(shù)值,并更新到結(jié)果編號(hào)列。
- 支持單個(gè)文件處理和批量文件處理。
for row_idx in range(2, ws.max_row + 1):
# Get the 序號(hào) value
序號(hào)_value = ws.cell(row=row_idx, column=序號(hào)_index).value
# Skip if 序號(hào) is None or empty
if 序號(hào)_value is None or str(序號(hào)_value).strip() == '':
continue
# Convert to string to handle any numeric values
序號(hào)_str = str(序號(hào)_value)
# Initialize count if this is the first occurrence
if 序號(hào)_str not in 序號(hào)_counts:
序號(hào)_counts[序號(hào)_str] = 0
# Increment the count
序號(hào)_counts[序號(hào)_str] += 1
# Create the new format: "序號(hào)-count"
new_子賬號(hào)編號(hào) = f"{序號(hào)_str}-{序號(hào)_counts[序號(hào)_str]}"
# Update the 子賬號(hào)編號(hào) cell
ws.cell(row=row_idx, column=子賬號(hào)編號(hào)_index).value = new_子賬號(hào)編號(hào)
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 '編號(hào)' not in headers or '結(jié)果編號(hào)' not in headers:
print("Error: Required columns '序號(hào)' or '結(jié)果編號(hào)' not found in the Excel file.")
return
序號(hào)_index = headers.index('編號(hào)') + 1 # +1 because openpyxl is 1-indexed
子賬號(hào)編號(hào)_index = headers.index('結(jié)果編號(hào)') + 1
# Create a dictionary to track occurrences of each 序號(hào)
序號(hào)_counts = {}
# Process each row (starting from row 2, skipping the header)
for row_idx in range(2, ws.max_row + 1):
# Get the 序號(hào) value
序號(hào)_value = ws.cell(row=row_idx, column=序號(hào)_index).value
# Skip if 序號(hào) is None or empty
if 序號(hào)_value is None or str(序號(hào)_value).strip() == '':
continue
# Convert to string to handle any numeric values
序號(hào)_str = str(序號(hào)_value)
# Initialize count if this is the first occurrence
if 序號(hào)_str not in 序號(hào)_counts:
序號(hào)_counts[序號(hào)_str] = 0
# Increment the count
序號(hào)_counts[序號(hào)_str] += 1
# Create the new format: "序號(hào)-count"
new_子賬號(hào)編號(hào) = f"{序號(hào)_str}-{序號(hào)_counts[序號(hào)_str]}"
# Update the 子賬號(hào)編號(hào) cell
ws.cell(row=row_idx, column=子賬號(hào)編號(hào)_index).value = new_子賬號(hào)編號(hào)
# 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實(shí)現(xiàn)自動(dòng)添加編號(hào)的文章就介紹到這了,更多相關(guān)Python Excel添加編號(hào)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基于DeepSeek大模型的提示詞優(yōu)化方案
以下基于DeepSeek大模型特性及搜索結(jié)果的綜合分析,結(jié)合提示詞設(shè)計(jì)原則、技術(shù)原理與優(yōu)化策略,提供完整Python代碼案例及詳細(xì)解析,需要的朋友可以參考下2025-04-04
關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說明
這篇文章主要介紹了關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
簡(jiǎn)單有效上手Python3異步asyncio問題
這篇文章主要介紹了簡(jiǎn)單有效上手Python3異步asyncio問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
Python爬蟲中Selenium實(shí)現(xiàn)文件上傳
這篇文章主要介紹了Python爬蟲中Selenium實(shí)現(xiàn)文件上傳,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Python用tkinter實(shí)現(xiàn)自定義記事本的方法詳解
這篇文章主要為大家詳細(xì)介紹了Python用tkinter實(shí)現(xiàn)自定義記事本的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03
搭建?Selenium+Python開發(fā)環(huán)境詳細(xì)步驟
這篇文章主要介紹了搭建?Selenium+Python開發(fā)環(huán)境詳細(xì)步驟的相關(guān)資料,需要的朋友可以參考下2022-10-10
Python3標(biāo)準(zhǔn)庫(kù)glob文件名模式匹配的問題
glob的模式規(guī)則與re模塊使用的正則表達(dá)式并不相同。實(shí)際上,glob的模式遵循標(biāo)準(zhǔn)UNIX路徑擴(kuò)展規(guī)則。只使用幾個(gè)特殊字符來實(shí)現(xiàn)兩個(gè)不同的通配符和字符區(qū)間。這篇文章主要介紹了Python3標(biāo)準(zhǔn)庫(kù)glob文件名模式匹配的知識(shí),需要的朋友可以參考下2020-03-03

