LoginSignup
0
0

PythonでWordの表を作成しカスタマイズする

Posted at

表はWordの強力なツールであり、情報の整理、提示、分析に役立ちます。この記事では、Pythonを使ってWordで表を作成し、そこにデータを入れる方法と、表のスタイルを設定する方法を説明します。

Python Wordライブラリ

Pythonを使用してWordでテーブルを作成または操作するには、まずサードパーティ製のライブラリSpire.Doc for Pythonをプロジェクトにインストールする必要があります。
pipコマンド:

pip install Spire.Doc

PythonでWordの表を作成する

import math
from spire.doc import *
from spire.doc.common import *
 
# Documentオブジェクトの作成
doc = Document()
 
# セクションの追加
section = doc.AddSection()
 
# 表を追加する
table = section.AddTable()
 
# テーブルデータの定義
header_data = ["製品名", "数量", "単価"]
row_data = [ ["A-01製品","20946","2.9"], 
                ["B-02製品","38931","1.5"], 
                ["B-11製品","32478","1.1"], 
                ["C-04製品","21162","0.6"], 
                ["D-05製品","66517","1.2"]]
                
# テーブルの行数と列数の設定
table.ResetCells(len(row_data) + 1, len(header_data))
 
# テーブルのオートフィットをウィンドウに設定する
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
 
# ヘッダー行を設定する
headerRow = table.Rows[0]
headerRow.IsHeader = True
headerRow.Height = 23
headerRow.RowFormat.BackColor = Color.get_LightGreen()
 
# ヘッダー行にデータを入力し、そのテキスト形式を設定する 
i = 0
while i < len(header_data):
    headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    paragraph = headerRow.Cells[i].AddParagraph()
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    txtRange = paragraph.AppendText(header_data[i])
    txtRange.CharacterFormat.Bold = True
    txtRange.CharacterFormat.FontSize = 12
    i += 1
 
# 残りの行をデータで埋め、テキスト形式を設定する
r = 0
while r < len(row_data):
    dataRow = table.Rows[r + 1]
    dataRow.Height = 20
    dataRow.HeightType = TableRowHeightType.Exactly
    c = 0
    while c < len(row_data[r]):
        dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = dataRow.Cells[c].AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        txtRange =  paragraph.AppendText(row_data[r][c])
        txtRange.CharacterFormat.FontSize = 11
        c += 1
    r += 1
 
# 行の色を交互に設定する
for j in range(1, table.Rows.Count):
    if math.fmod(j, 2) == 0:
        row2 = table.Rows[j]
        for f in range(row2.Cells.Count):
            row2.Cells[f].CellFormat.BackColor = Color.get_LightYellow()
 
# ファイルの保存
doc.SaveToFile("WordTable.docx", FileFormat.Docx2016)

上記の例では、まず Section.AddTable() メソッドでWord文書にテーブルを追加し、指定したセルにリストのデータを入力しています。さらに、Spire.Doc for Pythonライブラリは、テーブル/セルのスタイルを設定するインターフェースも提供しています。

出力結果:
Wordtable.png


Spire.Doc for Pythonライブラリは、Wordの表に対するその他の操作(行や列の追加、削除、コピー、セルの結合や分割など)もサポートしています。より多くのサンプルデモが利用可能です:

赤い透かしを消すための一時的なライセンスをリクエストする:
https://www.e-iceblue.com/TemLicense.html

0
0
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
0