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】Fontオブジェクトを使って文字の書式を統一する。

Posted at

pythonを使用してExcelファイルの操作を勉強しています。
本日の気づき(復習)は、書式に関してです。
pythonでExcelを操作するため、openpyxlというパッケージを使用しています。

Fontオブジェクト

文字の書式を設定するための使うのですが、想像以上に色々な引数が用意されていて
びっくりしました。

cell.font = Font(name=フォントの名前, color=RGB形式の色, size=サイズ, bold=太字にしたい場合はTrue)

メインで使用するのはこれくらいでしょうか。

class Font(name=None, sz=None, b=None, i=None, charset=None, u=None, strike=None, color=None, scheme=None, family=None, size=None, bold=None, italic=None, strikethrough=None, underline=None, vertAlign=None, outline=None, shadow=None, condense=None, extend=None)

こんなにあるの??

  • name :フォント名を文字列で指定
  • b(bold) :ボールド体(太文字)Trueで太字、Falseで戻る
  • i(italic) :イタリック体(斜体)Trueで斜体、Flaseで戻る
  • strike :打消し線 Trueで打消し線、Flaseで戻る
  • sz(size) :文字の大きさ サイズを数値で指定(小数可能)
  • u(underline):アンダーライン4種類ある
  • shadow :文字に影をつける Trueで影がつくっぽいですが分からないです。
  • vertAlign :上付き下付き文字の変更3種類ある
  • color :色コード文字列で指定
  • shceme :文字が薄く?細く?なるmajorで細く、minorで戻る
  • charset,family,outilne,extend,condense:わかりませんでした。

補足としては
u(underline):アンダーラインの4種類は

  1. 下線(文字列の長さ):single
  2. 二重線(文字列の長さ):double
  3. 下線(セルの長さ):singleAccoounting
  4. 二重線(セルの長さ):doubleAccoounting


vertAlign :上付き下付き文字の変更の3種類は

  1. superscript:上付き文字
  2. subscript:下付き文字
  3. baseline:元に戻る

でした。

流石に記述だけだと慣れるまではイメージしにくいですね。
そういう意味ではExcel考えた人って偉大ですね。

from openpyxl import load_workbook
from openpyxl.styles import Font

wb = load_workbook('商品リスト.xlsx')
ws = wb.active

# 文字の書式を生成
blue_font = Font(name='MS P明朝', color='0000FF', size=18, bold=True)

for row in ws['A1':'BB1']:
    for cell in row:
        cell.font = blue_font

wb.save('商品リスト_加工後.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?