LoginSignup
2
1

More than 3 years have passed since last update.

Python-docxで日本語フォントを使いたい

Posted at

はじめに

Python-docxを使って文書の自動生成プログラムを作っているとき、「MS 明朝じゃなくて、どうしてもMS Pゴシックいいのじゃ~」って言われたことはありませんか?
そんな時に、このプログラムを参考にしてもらえると幸いです。

環境

Python 3.7.2
pip install python-docx 済み

コード

pydocx_sample.py
import os
import sys

#word
from docx import Document
from docx.oxml.ns import qn


document = Document('tmp.docx')#余白とかのベースを拾う

para = document.add_paragraph()
run = para.add_run("あいうえお")
run.font.name = "MS Pゴシック"
run._element.rPr.rFonts.set(qn('w:eastAsia'), run.font.name)

document.save('sample.docx')

使い方

  1. こういう感じで、tmp.docxを作っておきます。
    image.png

  2. そして、pydocx_sample.pyを実行します。
    image.png

  3. すると、このようにsample.docxが生成できてます。
    image.png

  4. sample.docxの中身にも、MS Pゴシックで文字が入力できています。
    image.png
    ※なぜか最初の1行空いてしまいます。回避策を知っている方がいらっしゃったらご教授お願いします!

おまけ(表の挿入と入力)

python-docxを用いたwordの日本語フォント入力が楽にあるクラスを公開してます。こっちのクラスでは、表の入力にも対応しています。
pydocx_ja_font
↓こんな感じです。
image.png

より良いPython-docxライフを!

2
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
2
1