LoginSignup
6
3

More than 1 year has passed since last update.

Python-Docxのチートシート

Last updated at Posted at 2022-02-13

Python-Docxのチートシートをまとめてみた。あんま需要ないかな。

pythondocx.JPG

Python-docxでWordファイルを読み込み、作成、保存
import docx #Python-docxをインポート
doc = docx.Document("Sample.docx") #ドキュメントを読み込む
doc = docx.Document() #ドキュメントを新規作成
doc.save("Sample.docx") #ドキュメントを保存 ※()内を変えることで新規保存
段落、表、図を取得
print("段落の個数:", len(doc.paragraphs)) #paragraphsで段落を取得
print("表の個数:", len(doc.tables)) #tablesで表を取得
print("図の個数:", len(doc.inline_shapes)) #shapesで図を取得
段落の操作(paragraphs)
#全段落のテキストを取得
i= 0
for para in doc.paragraphs:
     i = i + 1
     print(i, para.text)

#特定の列のテキストを読み出し
print(doc.paragraphs[i].text)

#特定の列のテキストを変換
t = doc.paragraphs[i] .text
t = t.replace("変換元", "変換後")

#特定の段落番号に新たな段落を挿入
last_para = doc.paragraphs[i] #i-1番目の段落を指定
last_para.insert_paragraph_before("abc") #段落を挿入

#段落の位置を揃える ※WD_ALIGN_PARAGRAPHを使用
from docx.enum.text import WD_ALIGN_PARAGRAPH
para.alignment = WD_ALIGN_PARAGRAPH.LEFT #左に揃える
para.alignment = WD_ALIGN_PARAGRAPH.CENTER #中央に揃える
para.alignment = WD_ALIGN_PARAGRAPH.RIGHT #右に揃える

#runを用いてフォントを変更 ※フォントの異なる文字をrunとして識別
if run.bold: #もし太字(Bold体)の文字列を見つけたら
   run.bold = False #太字を解除
   run.underline = True #下線を追加
表の操作(tables)
#表の行・列を取得
tbl = doc.tables #tablesで表を取得
print("行数=", len(tbl.rows), "列数=", len(tbl.columns))
#rows=行、columns=列

#セルの値を取得
row.cells #対象行(row)のcellsでセルを取得
print(cell.text) #セル内のテキストを取得、表示

#セルのフォントを変更
for run in cell_para.runs: #runを識別
      if run.text:
         run.bold = True #太字にする
図の操作(inline_shape)
#図のサイズを取得、表示
img = doc.inline_shapes[0]
for img in doc.inline_shapes:
     num = num + 1
     print(num, "幅=", img.width, "高さ=", img.height)

#図のサイズを変更
img.width = int(img.width * 0.5)
img.height = int(img.height * 0.5)

参照元

Python-Docx公式(英語)
https://python-docx.readthedocs.io/en/latest/
python-docxによるWordファイル操作方法のまとめ
https://gammasoft.jp/support/how-to-use-python-docx-for-word-file/

参考

YouTubeで「Pythonを使った事務処理の効率化」というタイトルで、Python-Docxを紹介。

6
3
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
6
3