A Complete Python Solution for Converting Excel Numbers to Chinese Business Levels
The article explains a real‑world requirement to map numeric business levels to Chinese strings in Excel and provides two Python solutions—one using openpyxl for modern .xlsx files and another using win32com for legacy .xls files—complete with runnable code and execution results.
When preparing client data, the author encountered a need to translate numeric business levels (1‑4) into Chinese strings ("一级", "二级", "三级", "四级") within an Excel sheet. The problem was framed as an automation task: replace the numeric value in column A with the corresponding Chinese level in column B, starting from the second row.
Solution 1 – Pure local parsing with openpyxl (no Office required)
from openpyxl import load_workbook
# 1. 配置映射关系:数字 → 中文等级
level_map = {
1: "一级",
2: "二级",
3: "三级",
4: "四级"
}
excel_path = r"C:\Users\Desktop\业务等级表.xlsx"
def convert_level_xlsx():
# 打开表格,read_only=False 允许写入修改
wb = load_workbook(excel_path)
sheet = wb.active # 取当前激活工作表
# 从第2行开始遍历(第1行是表头)
for row in range(2, sheet.max_row + 1):
cell_a = sheet[f"A{row}"]
num = cell_a.value
# 判断单元格是数字再转换
if isinstance(num, int) and num in level_map:
sheet[f"B{row}"].value = level_map[num]
# 另存新文件,不覆盖原表
output_path = excel_path.replace('.xlsx', '_转换完成.xlsx')
wb.save(output_path)
wb.close()
print(f"✅ 转换完成,输出文件:{output_path}")
if __name__ == "__main__":
convert_level_xlsx()The script loads the workbook, iterates from row 2 to the last row, checks whether the value in column A is an integer present in level_map, and writes the corresponding Chinese string to column B. After processing, it saves the result to a new file whose name ends with “_转换完成.xlsx”. The author reports that the conversion runs without errors and the output file opens correctly.
Solution 2 – Compatibility with legacy .xls files using win32com
import os
import win32com.client
level_map = {
1: "一级",
2: "二级",
3: "三级",
4: "四级"
}
excel_path = r"C:\Users\Desktop\业务等级表.xls"
def kill_excel():
"""清理残留Excel进程,兼容WPS"""
import subprocess
try:
subprocess.call(["taskkill", "/f", "/im", "EXCEL.EXE"])
except Exception:
pass
def convert_level_xls():
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
excel.DisplayAlerts = 0
wb = excel.Workbooks.Open(os.path.abspath(excel_path))
sheet = wb.Worksheets(1)
max_row = sheet.Cells(sheet.Rows.Count, 1).End(-4162).Row # xlUp
for row in range(2, max_row + 1):
num = sheet.Cells(row, 1).Value
if isinstance(num, int) and num in level_map:
sheet.Cells(row, 2).Value = level_map[num]
output = excel_path.replace('.xls', '_转换完成.xls')
wb.SaveAs(os.path.abspath(output))
wb.Close()
del excel
kill_excel()
print(f"✅ 转换完成:{output}")
if __name__ == "__main__":
convert_level_xls()This approach launches a hidden Excel COM instance, opens the legacy .xls file, determines the last used row, performs the same mapping logic, saves the modified workbook under a new name, and finally terminates any lingering Excel processes to avoid file locks. The author confirms successful conversion and a clean output file.
Both methods are presented as complete, ready‑to‑run solutions. The author invites readers to try the code, share alternative implementations, and discuss further improvements in the comments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
