Python Excel数字格式化:金额千分位与百分比设置
用openpyxl的number_format把数字格式化成人民币金额、千分位、百分比、保留两位小数,避免直接显示原始浮点数,附完整代码。
场景痛点
Python 写进 Excel 的数字,默认就是一串裸数字:1234567.89 显示成 1234567.89,小数比例显示成 0.85。老板要看到的是 ¥1,234,567.89 和 85.0%。手动设单元格格式又慢又容易漏列。用 number_format,按列一次性套上格式,显示效果和手动设的一模一样,但底层数值没动。
用到的库
pip install openpyxl
完整代码
from openpyxl import load_workbook
def apply_number_format(file_path: str) -> None:
wb = load_workbook(file_path)
ws = wb.active
# 找列号
header = [c.value for c in ws[1]]
def col_of(name):
return header.index(name) + 1 if name in header else None
amount_col = col_of("金额")
rate_col = col_of("完成率")
qty_col = col_of("数量")
for row in range(2, ws.max_row + 1):
if amount_col:
c = ws.cell(row=row, column=amount_col)
# ¥#,##0.00 :人民币符号 + 千分位 + 两位小数
c.number_format = '¥#,##0.00'
if rate_col:
c = ws.cell(row=row, column=rate_col)
# 0.0% :把 0.85 显示成 85.0%
c.number_format = '0.0%'
if qty_col:
c = ws.cell(row=row, column=qty_col)
# 整数加千分位
c.number_format = '#,##0'
# 整列统一也可以直接对列维度设(不需要逐行)
# if amount_col:
# from openpyxl.utils import get_column_letter
# letter = get_column_letter(amount_col)
# ws.column_dimensions[letter].number_format = '¥#,##0.00'
wb.save(file_path)
print("数字格式已应用")
if __name__ == "__main__":
apply_number_format(r"D:\reports\销售明细.xlsx")
代码讲解
cell.number_format = "..."是 openpyxl 设置数字格式的属性,格式串就是 Excel 单元格格式里那一套,不需要记新语法。'¥#,##0.00':¥前缀人民币符号,#,##0整数部分带千分位逗号,.00固定两位小数。'0.0%':把 0.85 这种小数乘以 100 显示成85.0%;注意:底层值仍然是 0.85,不是 85,做计算时要清楚。'#,##0':整数千分位,不带小数。- 按列名找列号,再从第 2 行开始逐格赋格式;这种写法直观,但几万行时有点慢。
- 注释里给了另一种写法:直接对列维度
column_dimensions[letter].number_format设整列格式,性能更好,适合新建表时用。
运行结果
打开文件,「金额」列显示成 ¥1,234,567.89,「完成率」列显示成 85.0%,「数量」列显示成 1,234。点中某个格子,编辑栏里看到的还是原始数值,格式只是显示层。
注意事项
number_format只改显示,不改底层值;0.85显示成85%后,pandas 读出来仍然是0.85。- 百分比格式的底层值是 0~1 的小数;如果你写进去的是 85,套上
0.0%会显示成8500%,要么存 0.85,要么用'0.0"%"'这种纯文本写法。 - 格式串里的逗号、小数点都是英文半角,别用中文全角符号。
- 日期格式也走
number_format,但更推荐直接写datetime对象 +yyyy-mm-dd格式串,下一篇会讲。 - 已经是文本的数字(左对齐那种)套格式不会变数值,需要先转成数字。

更新时间:2026-09-15 09:05:11