Excelで表を作成する際に枠線に一部に基本の枠線以外を使うと意外と面倒だったりするので、数種類の線種を含めた表作成のコードを紹介します。 いつも作る表の形が決まっている方は参考にしてください。
1.アウトプット
まずは今回紹介する表とコードを紹介します。自分が良く使う外枠を太線、1行目の下線を二重線にした形で作りました。
from openpyxl import Workbook
from openpyxl.styles import Border, Side
Workbook()
wb = Workbook()
ws = wb.active
#列(col)、行(row)の始点、終点の定義(以下はB2~F7までを指定)
col_start = 2
col_end = 6
row_start = 2
row_end = 7
#-------線種定義-------
#パターンA:4辺全て細線
thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
#パターンB:1辺だけ太線のセルを左辺、右辺、上辺、下辺それぞれ作成
thick_left = Border(left=Side(style='thick '), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
thick_right = Border(left=Side(style='thin'), right=Side(style='thick '), top=Side(style='thin'), bottom=Side(style='thin'))
thick_top = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thick '), bottom=Side(style='double '))
thick_bottom = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thick '))
#パターンC:角2辺が太線のセルを左上、右上、左下、右下それぞれ作成
thick_ltop = Border(left=Side(style='thick '), right=Side(style='thin'), top=Side(style='thick '), bottom=Side(style='double'))
thick_rtop = Border(left=Side(style='thin'), right=Side(style='thick '), top=Side(style='thick '), bottom=Side(style='double '))
thick_lbottom = Border(left=Side(style='thick '), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thick '))
thick_rbottom = Border(left=Side(style='thin'), right=Side(style='thick '), top=Side(style='thin'), bottom=Side(style='thick '))
#-------表作成-------
#パターンAを使い全て細線の表作成
for row in range(row_start, row_end+1):
for col in range(col_start, col_end+1):
cell = ws.cell(row=row, column=col)
cell.border = thin_border
#パターンBを使い外枠の左辺、右辺が太線の表作成
for row in range(row_start, row_end+1):
ws.cell(row=row, column=col_start).border = thick_left
ws.cell(row=row, column=col_end).border = thick_right
#パターンBを使い外枠の上辺、下辺が太線の表作成
for col in range(col_start, col_end+1):
ws.cell(row=row_start, column=col).border = thick_top
ws.cell(row=row_end, column=col).border = thick_bottom
#パターンCを使い外枠の2辺が太線の作成
ws.cell(row=row_start, column=col_start).border = thick_ltop
ws.cell(row=row_start, column=col_end).border = thick_rtop
ws.cell(row=row_end, column=col_start).border = thick_lbottom
ws.cell(row=row_end, column=col_end).border = thick_rbottom
wb.save('C:/Users/1/Desktop/python/openpyxl/表作成.xlsx')
2.表作成の工程
見た目は簡単な表ですが、ずいぶんと長いコードになってしまいました。コードが長いので表作成の工程を説明すると、 細線のグラフ作成→外枠の左右、上下の辺を太線→四隅の角を太線 の手順で作成した表を重ねていくことで目的の形を作っています。
範囲指定の定義や関数化することでもっとスッキリしたコードにできるかもしれませんが、定義する範囲をセル番号をそのまま書き出せば良かったり、表を分解してそれぞれの線種を定義することで形を変えやすかったりと
メリット ・作りが単純 ・カスタマイズが容易 デメリット ・コードが長い
と言った特徴があります。ただし、表作成の頻度が少ない自分としてはカスタマイズが簡単な方が毎回作り方を調べて理解しなくていいので、この形をテンプレートとして利用しています。
3.終わりに
今回は表を作成するコードのサンプルを紹介しました。コードが長く手間なので、たまに表を作成する人がコードを調べると逆に時間がかかるかもしれないので、今回紹介したコードを活用してもらえると嬉しいです。