表内のテキストを操作する
以前の記事で述べたように、表には通常プレーン テキストが含まれますが、画像や他の表などの他のコンテンツを表のセルに配置することもできます。
テーブルへのテキストまたはその他のコンテンツの追加は、DocumentBuilder クラスの適切なメソッドを使用して実行されます。これについては、「テーブルを作成する」 の記事で説明されています。この記事では、既存の表内のテキストを操作する方法について説明します。
表内のテキストを置換する
テーブルは、Aspose.Words の他のノードと同様に、Range オブジェクトにアクセスできます。テーブル範囲オブジェクトを使用すると、テーブル内のテキストを置換できます。
置換時に特殊文字を使用する機能は現在サポートされているため、既存のテキストを複数段落のテキストに置き換えることができます。これを行うには、対応する Replace メソッドで説明されている特別なメタキャラクタを使用する必要があります。
次のコード例は、テーブル全体のセル内のテキスト文字列のすべてのインスタンスを置換する方法を示しています。
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git. | |
doc = aw.Document(MY_DIR + "Tables.docx") | |
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table() | |
table.range.replace("Carrots", "Eggs", aw.replacing.FindReplaceOptions(aw.replacing.FindReplaceDirection.FORWARD)) | |
table.last_row.last_cell.range.replace("50", "20", aw.replacing.FindReplaceOptions(aw.replacing.FindReplaceDirection.FORWARD)) | |
doc.save(ARTIFACTS_DIR + "FindAndReplace.replace_text_in_table.docx") |
テーブルまたはセルからプレーンテキストを抽出する
Range オブジェクトを使用すると、テーブル範囲全体でメソッドを呼び出し、テーブルをプレーン テキストとして抽出することもできます。これを行うには、Text プロパティを使用します。
次のコード例は、表のテキスト範囲を印刷する方法を示しています。
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git. | |
doc = aw.Document(MY_DIR + "Tables.docx") | |
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table() | |
# The range text will include control characters such as "\a" for a cell. | |
# You can call ToString and pass SaveFormat.text on the desired node to find the plain text content. | |
print("Contents of the table: ") | |
print(table.range.text) |
同じ手法を使用して、表の個々のセルのみからコンテンツを抽出します。
次のコード例は、行要素とテーブル要素のテキスト範囲を印刷する方法を示しています。
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git. | |
print("\nContents of the row: ") | |
print(table.rows[1].range.text) | |
print("\nContents of the cell: ") | |
print(table.last_row.last_cell.range.text) |
代替テーブルテキストの操作
Microsoft Word テーブルには、テーブルに含まれる情報の代替テキスト表現を提供する table title
と table description
があります。
Aspose.Words では、Title プロパティと Description プロパティを使用してテーブルのタイトルと説明を追加することもできます。これらのプロパティは、ISO/IEC 29500 に準拠する DOCX ドキュメントにとって重要です。ISO/IEC 29500 より前の形式で保存する場合、これらのプロパティは無視されます。
次のコード例は、テーブルのタイトルと説明のプロパティを設定する方法を示しています。
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git. | |
doc = aw.Document(MY_DIR + "Tables.docx") | |
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table() | |
table.title = "Test title" | |
table.description = "Test description" | |
options = aw.saving.OoxmlSaveOptions() | |
options.compliance = aw.saving.OoxmlCompliance.ISO29500_2008_STRICT | |
doc.compatibility_options.optimize_for(aw.settings.MsWordVersion.WORD2016) | |
doc.save(ARTIFACTS_DIR + "WorkingWithTableStylesAndFormatting.table_title_and_description.docx", options) |