速戰速決 Python - python 第三方庫(openpyxl): excel樣式處理
阿新 • • 發佈:2022-01-20
速戰速決 Python - python 第三方庫(openpyxl): excel樣式處理
速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd
速戰速決 Python - python 第三方庫(openpyxl): excel樣式處理
示例如下:
thirdLib/openpyxl/sample2.py
# openpyxl - excel 樣式處理 from openpyxl import * from openpyxl.styles import * import sys path = sys.path[0] + "\demo2.xlsx" wb = Workbook() sheet1 = wb.active sheet1.title = "sheet1" for i in range(1, 100): for j in range(1, 10): sheet1.cell(i, j).value = f'{i}_{j}' # 指定行的行高 sheet1.row_dimensions[1].height = 40 # 指定列的列寬 sheet1.column_dimensions['A'].width = 40 # 單元格的對齊方式 # horizontal 可選值 'fill', 'distributed', 'centerContinuous', 'right', 'justify', 'center', 'left', 'general' # vertical 可選值 'distributed', 'justify', 'center', 'bottom', 'top' sheet1.cell(1, 1).alignment = Alignment(horizontal='center', vertical='center') # 單元格的字型 # name - 字型名稱 # size - 字型大小 # color - 字型顏色 # b - 是否粗體 # i - 是否斜體 sheet1.cell(1, 1).font = Font(name='微軟雅黑', size=24, color=Color(rgb='ff0000'), b=True, i=True) # 單元格的邊框 # style - 邊框樣式,可選值 'dashDot','dashDotDot', 'dashed','dotted', 'double','hair', 'medium', 'mediumDashDot', 'mediumDashDotDot', 'mediumDashed', 'slantDashDot', 'thick', 'thin' # color - 邊框顏色 sheet1.cell(1, 1).border = Border(left=Side(), top=Side(), right=Side(), bottom=Side(style='thick', color='ff0000')) # 單元格的填充 # fgColor - 填充的顏色 sheet1.cell(1, 1).fill = PatternFill(fgColor='00ff00') # 定義樣式 myStyle = NamedStyle( name='my_style', font=Font(color='ff0000'), fill=PatternFill(fgColor='00ff00'), border=Border(left=Side(style='medium',color='0000ff')), alignment=Alignment(horizontal='center', vertical='center') ) # 單元格的樣式 sheet1.cell(2, 1).style = myStyle # 通過樣式物件設定樣式 sheet1.cell(3, 1).style = "my_style" # 通過樣式名稱設定樣式 # cell.has_style - 單元格是否存在樣式 # cell.style - 獲取單元格的樣式名稱 print(sheet1.cell(3, 1).has_style, sheet1.cell(2, 1).style) # True my_style # 數字格式 sheet1.cell(1, 2).value = 1234.1234 print(sheet1.cell(1, 2).number_format) # General sheet1.cell(1, 2).number_format = '#,##0.00' # 在 excel 中單元格顯示 1,234.12 # 日期也屬於數字格式 import datetime sheet1.cell(2, 2).value = datetime.datetime(2012, 12, 21, 10, 0, 0, 0) sheet1.cell(2, 2).number_format = 'yyyy-MM-dd HH:mm:ss' # 在 excel 中單元格顯示 2012-12-21 10:00:00 # 儲存 excel wb.save(path)
速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd