異なる形式のドキュメント間でデータを移行することは、非常に重要な操作です。たとえば、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文書にインポートすることが可能です。操作手順の例を以下に示します。
- 必要なモジュールをインポートします。
-
Document
オブジェクトを作成し、新しいWord文書を作成します。 -
Document.AddSection()
メソッドを使用して文書内にセクションを作成し、Section.AddTable()
メソッドを使用してセクション内に表を作成します。 - 表のヘッダーセルとデータ行セルのテキストスタイルを設定します。
- ヘッダーデータを表に書き込み、フォーマットを設定します。
- その他のデータを表に書き込み、フォーマットを設定します。
-
Table.AutoFit(AutoFitBehaviorType)
メソッドを使用して表の自動調整を設定します。 -
Document.SaveToFile()
メソッドを使用して文書を保存します。 - リソースを解放します。
コード例
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()
Pythonを使用してExcelデータをWordの表にインポートする方法
Excelファイルの表データをWord文書にインポートする場合も、似た手順で操作を行います。この操作では、Spire.XLS for Python(PyPI:pip install Spire.XLS
)を使用してExcelワークシートのデータを読み込み、Word文書の表に書き込みます。以下は操作手順の例です。
- 必要なモジュールをインポートします。
-
Document
オブジェクトを作成し、新しいWord文書を作成します。 -
Document.AddSection()
メソッドを使用して文書内にセクションを作成し、Section.AddTable()
メソッドを使用してセクション内に表を作成します。 -
Workbook
オブジェクトを作成し、Workbook.LoadFromFile()
メソッドを使用してExcelファイルを読み込みます。 -
Workbook.Worksheets.get_Item()
メソッドを使用してワークシートを取得します。 - 表のヘッダーセルとデータ行セルのテキストスタイルを設定します。
- ヘッダーデータを表に書き込み、フォーマットを設定します。
- その他のデータを表に書き込み、フォーマットを設定します。
-
Table.AutoFit(AutoFitBehaviorType)
メソッドを使用して表の自動調整を設定します。 -
Document.SaveToFile()
メソッドを使用して文書を保存します。 - リソースを解放します。
コード例
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()
本記事では、Pythonを使用してCSVやExcelの表データをWord文書にインポートし、表を作成する方法について紹介しました。
さらにWord文書の処理方法に関する技術を学びたい方は、Spire.Doc for Pythonのチュートリアルをご覧ください。