0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonでExcel操作【openpyxl - セルのスタイルを制御する】

Posted at

概要

openpyxl.styles.配下に様々なモジュールが用意されており、それぞれ呼び出して設定していく。
全てのモジュールの詳細は:openpyxl公式ドキュメント

実装後イメージ

sample3.png

### コード

import openpyxl as xl
book = xl.Workbook()
sheet = book.active

# 幅(B列の)
sheet.column_dimensions["B"].width = 40 
# 高さ
sheet.row_dimensions[2].height = 40

cell = sheet["B2"]
cell.value = "テスト文字列"

# テキスト配置
from openpyxl.styles.alignment import Alignment
cell.alignment = Alignment( # Aligment === xl.stylex.Alignment
    horizontal = "center", # 水平位置
    vertical = "center" # 垂直位置
)
# 羅線
from openpyxl.styles.borders import Border, Side # Border = 罫線, Side = 罫線スタイル
cell.border = Border(
    top = Side(style = "thin", color = "000000"), # Sideを代入しないと "TypeError: expected <class 'openpyxl.styles.borders.Side'>"
    right = Side(style = "thin", color = "000000"),
    left = Side(style = "thin", color = "000000"),
    bottom = Side(style = "thin", color = "000000") 
)
# フォント
from openpyxl.styles import Font
cell.font = Font(
    size = 14,
    bold = True,
    italic = True,
    color = "FFFFFF" # 白
)
# 背景色
from openpyxl.styles import PatternFill
cell.fill = PatternFill(
    fill_type = "solid", # ベタ塗り
    fgColor = "FF0000" # 赤
)

book.save("cell_style.xlsx")
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?