PythonでExcelにオリジナルのテーブルスタイルを追加する
Info
Excelのリストオブジェクト(テーブルスタイル)って何?という方はブログに書いたのでそちら見てください
右の2つがオリジナルのテーブルスタイル
これをPowerShellで以下のように実行すると適用できるようにりなます
python .\excelActivebookAddTableStyle.py
事前準備・確認
- まだPythonとxlwingsをインストールしていなければしておく
Pythonがインストールされているかの確認
- 以下が実行できてバージョンが表示されればOK
-
python --version
-
xlwingsがインストールされているかの確認
- 以下を実行してxlwingsが含まれていればOK
-
pip list
- 実行後の表示例
-
Package Version
------- -------
pip 25.0.1
pywin32 310
xlwings 0.33.11
-
-
フォルダー構成
保存場所はpythonが実行できればどこでもOKです
直接実行する excelActivebookAddTableStyle.py
と同じ階層に modules
フォルダーがあれば実行できます
/
├ excelActivebookAddTableStyle.py
└ modules
├ addTableStyle.py
├ addTableStyleLightBlue.py
└ addTableStyleLightGreen.py
フォルダー構成通りにファイルをコピーする
各ソースはコチラ
excelActivebookAddTableStyle.py
# Example usage:
# python .\excelActivebookAddTableStyle.py
# Debugging:
# python .\excelActivebookAddTableStyle.py --debug
import argparse
import xlwings as xw
from modules.addTableStyleLightGreen import addTableStyleLightGreen
from modules.addTableStyleLightBlue import addTableStyleLightBlue
def main(debug: bool):
# 既に起動しているExcelアプリケーションに接続
# Connect to an already running Excel application
try:
app = xw.apps.active # アクティブなExcelインスタンスを取得
# app = xw.apps.active # Get active Excel instance
if debug:
print("INFO: Connected to Excel application")
except Exception as e:
raise RuntimeError("ERROR: Excelが起動していません。Excelを起動してください。") from e
# raise RuntimeError(“ERROR: Excel is not running, please start Excel.”) from e
# アクティブなブックを取得
# Get the active book
try:
wb = app.books.active
bok = wb.api # ここで underlying COM オブジェクトを取得
# bok = wb.api # get underlying COM object here
if debug:
print(f"INFO: Active workbook obtained: {bok.Name}")
except Exception as e:
print(f"ERROR: Failed to get active workbook: {e}")
raise
# テーブルスタイルを適用する関数を呼び出す
# Call a function to apply a table style
try:
style_name = addTableStyleLightBlue(bok, debug)
if debug:
print(f"INFO: Added style: {style_name}")
except Exception as e:
print(f"ERROR: Failed to add TableStyleLightBlue style: {e}")
try:
style_name = addTableStyleLightGreen(bok, debug)
if debug:
print(f"INFO: Added style: {style_name}")
except Exception as e:
print(f"ERROR: Failed to add TableStyleLightGreen style: {e}")
# COMオブジェクトの解放
# Release COM object
finally:
bok = None
if debug:
print("INFO: COM objects released")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Excel Table Style Adder")
parser.add_argument('--debug', action='store_true', help="Enable debug mode")
args = parser.parse_args()
main(args.debug)
modules/addTableStyle.py
def RGB(r, g, b):
# VBA の RGB(r, g, b) は r + (g * 256) + (b * 65536) と同等です
# RGB(r, g, b) in VBA is equivalent to r + (g * 256) + (b * 65536)
return r + (g << 8) + (b << 16)
# 定数(enum相当):
# Constants (equivalent to enum):
XL_WHOLE_TABLE = 0
XL_HEADER_ROW = 1
XL_TOTAL_ROW = 2
XL_ROW_STRIPE1 = 5
XL_EDGE_LEFT = 7
XL_EDGE_TOP = 8
XL_EDGE_BOTTOM = 9
XL_EDGE_RIGHT = 10
XL_INSIDE_VERTICAL = 11
XL_INSIDE_HORIZONTAL = 12
XL_HAIRLINE = 1
# 色情報用のクラス
# Color information class
class Colors:
def __init__(self, font, line, back_dark, back_light):
self.font = font
self.line = line
self.back_dark = back_dark
self.back_light = back_light
def addTableStyle(bok, style_name, colors, debug=False):
"""
bok: Excel COM object
style_name: Name of table style to be created
colors: Colors object
debug: true=debug mode, false=normal mode
"""
if debug:
print(f"INFO: Adding table style: {style_name}")
# 既存の同名スタイルがあれば削除する
# Remove existing style with same name if any
try:
existing_style = bok.TableStyles(style_name)
existing_style.Delete()
if debug:
print(f"INFO: Existing style '{style_name}' deleted")
except Exception as e:
pass
# 新しいテーブルスタイルを追加
# Add new table style
try:
table_style = bok.TableStyles.Add(style_name)
if debug:
print(f"INFO: Table style added successfully. table_style name: {table_style.Name}")
except Exception as e:
print(f"ERROR: Failed to add table style: {e}")
raise
# 全利用シーンで使用可能
# Can be used in all usage scenarios
table_style.ShowAsAvailableTableStyle = True
table_style.ShowAsAvailablePivotTableStyle = True
table_style.ShowAsAvailableSlicerStyle = False
table_style.ShowAsAvailableTimelineStyle = False
# 全体のテーブル要素の設定
# Setup of entire table elements
elem = table_style.TableStyleElements(XL_WHOLE_TABLE)
elem.Borders(XL_EDGE_TOP).Color = colors.line
elem.Borders(XL_EDGE_BOTTOM).Color = colors.line
elem.Borders(XL_EDGE_LEFT).Color = colors.line
elem.Borders(XL_EDGE_RIGHT).Color = colors.line
elem.Borders(XL_INSIDE_VERTICAL).Color = colors.line
elem.Borders(XL_INSIDE_VERTICAL).Weight = XL_HAIRLINE
elem.Borders(XL_INSIDE_HORIZONTAL).Color = colors.line
elem.Borders(XL_INSIDE_HORIZONTAL).Weight = XL_HAIRLINE
# 行ストライプ要素の設定
# Set row stripe elements
elem = table_style.TableStyleElements(XL_ROW_STRIPE1)
elem.Interior.Color = colors.back_light
# ヘッダ行要素の設定
# Set header row element
elem = table_style.TableStyleElements(XL_HEADER_ROW)
elem.Clear()
elem.Interior.Color = colors.back_dark
elem.Borders(XL_EDGE_BOTTOM).Color = colors.line
fo = elem.Font
fo.FontStyle = "太字"
# fo.FontStyle = "bold"
fo.Color = colors.font
# トータル行要素の設定
# Set total line element
elem = table_style.TableStyleElements(XL_TOTAL_ROW)
elem.Clear()
elem.Interior.Color = colors.back_dark
elem.Borders(XL_EDGE_BOTTOM).Color = colors.line
fo = elem.Font
fo.FontStyle = "太字"
# fo.FontStyle = "bold"
fo.Color = colors.font
print(f"テーブルスタイルの登録成功: {style_name}")
# print(f"Table style registration succeeded: {style_name}")
return style_name
modules/addTableStyleLightBlue.py
from modules.addTableStyle import addTableStyle, Colors, RGB
import os
def addTableStyleLightBlue(bok, debug=False):
if debug:
print(f"INFO: {os.path.basename(__file__)} - テーブルスタイル追加")
# print(f"INFO: {os.path.basename(__file__)} - Additional table style")
colors = Colors(
font=RGB(31, 78, 120),
line=RGB(155, 194, 230),
back_dark=RGB(152, 192, 228),
back_light=RGB(221, 235, 247)
)
return addTableStyle(bok, "TableStyleLightBlue", colors, debug)
modules/addTableStyleLightGreen.py
from modules.addTableStyle import addTableStyle, Colors, RGB
import os
def addTableStyleLightGreen(bok, debug=False):
if debug:
print(f"INFO: {os.path.basename(__file__)} - テーブルスタイル追加")
# print(f"INFO: {os.path.basename(__file__)} - Additional table style")
colors = Colors(
font=RGB(55, 86, 35),
line=RGB(112, 173, 71),
back_dark=RGB(198, 224, 180),
back_light=RGB(248, 255, 242)
)
return addTableStyle(bok, "TableStyleLightGreen", colors, debug)
各ソースの解説
excelActivebookAddTableStyle.py
- 実行ファイル
- これでテーブルスタイルを追加する
- addTableStyleLightBlue.py以外にもファイルが増えればこのファイルも編集してそのファイルも実行するようにする
Call a function to apply a table style
の箇所
addTableStyle.py
- テーブルスタイルを適用する本体
- 実装部。Pythonで書いてあるけど、VBAで書く場合とほとんど同じです
addTableStyleLightBlue.py
- テーブルスタイルごとのファイル
- 実装部とデザイン部を切り分けてこちらはデザイン。RGBを指定するだけ
font=RGB(31, 78, 120)
など
- 色を指定し、addTableStyleを使ってテーブルスタイルを作る
実行方法
- 適用させたいExcelブックを開き、アクティブにしておく
- PowerShellで以下を実行する
-
python .\excelActivebookAddTableStyle.py
-
- 実行後、ユーザー設定が追加されていれば成功