註
border_style是線條樣式,可參考"設定儲存格格式"外框頁次線條欄位的樣式
Border(left=Side(border_style=None,color='000000'), #儲存格左邊框線
right=Side(border_style=None,color='000000'), #儲存格右邊框線
top=Side(border_style=None,color='000000'), #儲存格上邊框線
botten=Side(border_style=None,color='000000'), #儲存格下邊框線
diagonal=Side(border_style=None,color='000000'),#儲存格對角框線
diagonalDown=False, #左上到右下的對角線,預設False,表示不顯示
diagonalUp=False, #左下到右上的對角線,預設False,表示不顯示
outline=Side(border_style=None,color='000000'), #儲存格垂直框線
vertical=Side(border_style=None,color='000000'),#儲存格水平框線
horizonal=Side(border_style=None,color='000000'))
ws[儲存格].border = Border(xx)
# xx是框線的系列屬性設定
也就是工作表的儲存格物件
引用 border
屬性,再執行賦值
設定。設定 Border框線時,只能單一儲存格設定,因為單一儲存格才有 border 屬性,如果要設定儲存格區間需使用迥圈方式。
#ch3_9.py
import openpyxl
from openpyxl.styles import Border,Side
fn = "out1_5.xlsx"
wb = openpyxl.load_workbook(fn)
ws = wb.active
#設定thin框線
side = Side(border_style='thin')
borders = Border(left=side,right=side,top=side,bottom=side)
for rows in ws['A1':'D10']:
for cell in rows:
cell.border = borders
#設定左上到右下的紅色對角線
diagonal_side = Side(border_style='thin', color="FF0000")
for cell in ws['A2':'D2']:
for c in cell:
c.border = Border(left=side, right=side, top=side, bottom=side, diagonal=diagonal_side, diagonalDown=True)
wb.save('out3_9.xlsx')