0
0

Pythonを使用してCSVやExcelの表をWord文書にインポートする方法

Posted at

異なる形式のドキュメント間でデータを移行することは、非常に重要な操作です。たとえば、CSVやExcelの表データをWord文書にインポートすることで、データの統合と表示を効率的に行い、作業効率と文書の専門性を大幅に向上させることができます。レポートの作成、統計分析の実施、ビジネス文書の編纂など、Pythonを使ってこれらの一般的なドキュメントのデータを処理するスキルを身に付ければ、情報の管理と提示がより柔軟になり、さまざまなニーズに対応できます。本記事では、Pythonを使用してCSVやExcelの表データをWord文書にインポートし、表を作成する方法について紹介します。

ここで紹介する方法では、Spire.Doc for Pythonを使用します。PyPI:pip install Spire.Doc

Pythonを使用してCSVデータをWordの表にインポートする方法

CSVファイルの表データは、Python標準ライブラリのcsvモジュールを使って直接文字列として読み込むことができます。次に、Spire.Doc for Pythonのメソッドとプロパティを使用して、読み込んだデータをもとにWord文書内に表を作成することで、CSVの表データをWord文書にインポートすることが可能です。操作手順の例を以下に示します。

  1. 必要なモジュールをインポートします。
  2. Documentオブジェクトを作成し、新しいWord文書を作成します。
  3. Document.AddSection()メソッドを使用して文書内にセクションを作成し、Section.AddTable()メソッドを使用してセクション内に表を作成します。
  4. 表のヘッダーセルとデータ行セルのテキストスタイルを設定します。
  5. ヘッダーデータを表に書き込み、フォーマットを設定します。
  6. その他のデータを表に書き込み、フォーマットを設定します。
  7. Table.AutoFit(AutoFitBehaviorType)メソッドを使用して表の自動調整を設定します。
  8. Document.SaveToFile()メソッドを使用して文書を保存します。
  9. リソースを解放します。

コード例

from spire.doc import *
import csv

# CSV表データを読み込む
with open('Sample.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    tableData = []
    for row in reader:
        tableData.append(row)

# Documentインスタンスを作成
doc = Document()

# 章と表を追加
section = doc.AddSection()
table = section.AddTable()

# 表ヘッダーとセル用の段落スタイルを作成
headerStyle = ParagraphStyle(doc)
headerStyle.Name = "TableHeader"
headerStyle.CharacterFormat.FontName = "Arial"
headerStyle.CharacterFormat.FontSize = 12
headerStyle.CharacterFormat.Bold = True
doc.Styles.Add(headerStyle)
cellStyle = ParagraphStyle(doc)
cellStyle.Name = "TableCell"
cellStyle.CharacterFormat.FontName = "Arial"
cellStyle.CharacterFormat.FontSize = 11
doc.Styles.Add(cellStyle)

# 表にヘッダー行を追加
headerRow = tableData[0]
tableRow = table.AddRow()
for cell in headerRow:
    tableCell = tableRow.AddCell()
    paragraph = tableCell.AddParagraph()
    paragraph.AppendText(cell)
    paragraph.ApplyStyle(headerStyle.Name)
    tableCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    tableCell.CellFormat.Borders.BorderType(BorderStyle.Single)
    tableCell.CellFormat.Borders.Color = Color.get_Black()
    tableCell.CellFormat.Borders.LineWidth(1.8)

# 表にデータ行を追加
for row in tableData[1:]:
    tableRow = table.AddRow()
    for cell in row:
        tableCell = tableRow.Cells[row.index(cell)]
        paragraph = tableCell.AddParagraph()
        paragraph.AppendText(cell)
        paragraph.ApplyStyle(cellStyle.Name)
        tableCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        tableCell.CellFormat.Borders.BorderType(BorderStyle.Single)
        tableCell.CellFormat.Borders.Color = Color.get_Black()
        tableCell.CellFormat.Borders.LineWidth(0.8)

# 表のサイズを自動調整
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)

# 文書を保存
doc.SaveToFile("output/CSVToWordTable.docx", FileFormat.Docx2019)
doc.Close()

結果文書
2024-08-30_175249.png

Pythonを使用してExcelデータをWordの表にインポートする方法

Excelファイルの表データをWord文書にインポートする場合も、似た手順で操作を行います。この操作では、Spire.XLS for Python(PyPI:pip install Spire.XLS)を使用してExcelワークシートのデータを読み込み、Word文書の表に書き込みます。以下は操作手順の例です。

  1. 必要なモジュールをインポートします。
  2. Documentオブジェクトを作成し、新しいWord文書を作成します。
  3. Document.AddSection()メソッドを使用して文書内にセクションを作成し、Section.AddTable()メソッドを使用してセクション内に表を作成します。
  4. Workbookオブジェクトを作成し、Workbook.LoadFromFile()メソッドを使用してExcelファイルを読み込みます。
  5. Workbook.Worksheets.get_Item()メソッドを使用してワークシートを取得します。
  6. 表のヘッダーセルとデータ行セルのテキストスタイルを設定します。
  7. ヘッダーデータを表に書き込み、フォーマットを設定します。
  8. その他のデータを表に書き込み、フォーマットを設定します。
  9. Table.AutoFit(AutoFitBehaviorType)メソッドを使用して表の自動調整を設定します。
  10. Document.SaveToFile()メソッドを使用して文書を保存します。
  11. リソースを解放します。

コード例

from spire.doc import Document, ParagraphStyle, VerticalAlignment, BorderStyle, Color, FileFormat
from spire.xls import Workbook

# Documentインスタンスを作成
doc = Document()

# 章と表を追加
section = doc.AddSection()
table = section.AddTable()

# Workbookインスタンスを作成し、Excelファイルをロード
workbook = Workbook()
workbook.LoadFromFile("Sample.xlsx")

worksheet = workbook.Worksheets.get_Item(0)

# 表ヘッダーとセル用の段落スタイルを作成
headerStyle = ParagraphStyle(doc)
headerStyle.Name = "TableHeader"
headerStyle.CharacterFormat.FontName = "Arial"
headerStyle.CharacterFormat.FontSize = 12
headerStyle.CharacterFormat.Bold = True
doc.Styles.Add(headerStyle)
cellStyle = ParagraphStyle(doc)
cellStyle.Name = "TableCell"
cellStyle.CharacterFormat.FontName = "Arial"
cellStyle.CharacterFormat.FontSize = 11
doc.Styles.Add(cellStyle)

print(worksheet.AllocatedRange.ColumnCount)
print(worksheet.AllocatedRange.RowCount)

headerRow = table.AddRow()
for i in range(worksheet.AllocatedRange.ColumnCount):
    cell = headerRow.AddCell()
    paragraph = cell.AddParagraph()
    paragraph.AppendText(worksheet.AllocatedRange.get_Item(1, i + 1).Text)
    paragraph.ApplyStyle(headerStyle.Name)
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    cell.CellFormat.Borders.BorderType(BorderStyle.Single)
    cell.CellFormat.Borders.Color = Color.get_Black()
    cell.CellFormat.Borders.LineWidth(1.8)

for j in range(1, worksheet.AllocatedRange.RowCount):
    dataRow = table.AddRow()
    for k in range(worksheet.AllocatedRange.ColumnCount):
        cell = dataRow.Cells.get_Item(k)
        paragraph = cell.AddParagraph()
        paragraph.AppendText(worksheet.AllocatedRange.get_Item(j + 1, k + 1).Value)
        paragraph.ApplyStyle(cellStyle.Name)
        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        cell.CellFormat.Borders.BorderType(BorderStyle.Single)
        cell.CellFormat.Borders.Color = Color.get_Black()
        cell.CellFormat.Borders.LineWidth(0.8)

# 表のサイズを自動調整
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)

# 文書を保存
doc.SaveToFile("output/ExcelTableToWord.docx", FileFormat.Docx2019)
doc.Close()

結果文書
2024-08-30_175151.png

本記事では、Pythonを使用してCSVやExcelの表データをWord文書にインポートし、表を作成する方法について紹介しました。

さらにWord文書の処理方法に関する技術を学びたい方は、Spire.Doc for Pythonのチュートリアルをご覧ください。

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