openpyxl 修改单元格格式(隐藏小数、设定百分数位数)

修改单元格格式(隐藏小数、设定百分数位数)

from openpyxl.styles import colors
from openpyxl.styles import Font, Color,PatternFill
from openpyxl.styles import colors 
from openpyxl import load_workbook
from openpyxl.styles import numbers


# 设定单元格格式
def set_number_format(file,sheet_index,dyg,new_format):
    wb = load_workbook(file)
    sheet_names = wb.get_sheet_names()
    # print(sheet_names)
    ws = wb.get_sheet_by_name(sheet_names[sheet_index])
    cell = ws[dyg]
    # 使用openpyxl内置的格式
    print('该单元格原格式',cell.number_format)
    # 修改单元格格式
    # 百分数:'0.00%'
    # 保留整数:'0_);[Red]\(0\)'
    cell.number_format = new_format
    wb.save(file)
    wb.close()




数值只保留整数
cell.number_format = ‘0_);[Red](0)’
保留两位小数
cell.number_format = ‘0.00%’