速戰速決 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章