列と行の操作

テーブルの動作をより詳細に制御するには、列と行を操作する方法を学習します。

テーブル要素インデックスの検索

列、行、およびセルは、選択したドキュメントノードにインデックスでアクセスすることによって管理されます。 ノードのインデックスを見つけるには、親ノードから要素タイプのすべての子ノードを収集し、IndexOfメソッドを使用してコレクション内の目的のノードのイン

ドキュメント内のテーブルのインデックスを検索する

場合によっては、ドキュメント内の特定のテーブルに変更を加える必要があることがあります。 これを行うには、そのインデックスでテーブルを参照できます。

次のコード例は、ドキュメント内のテーブルのインデックスを取得する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
SharedPtr<NodeCollection> allTables = doc->GetChildNodes(NodeType::Table, true);
int tableIndex = allTables->IndexOf(table);

テーブル{#find-the-index-of-a-row-in-a-table}内の行のインデックスを検索します

同様に、選択したテーブルの特定の行に変更を加える必要がある場合があります。 これを行うには、そのインデックスで行を参照することもできます。

次のコード例は、テーブル内の行のインデックスを取得する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
int rowIndex = table->IndexOf(table->get_LastRow());

行{#find-the-index-of-a-cell-in-a-row}のセルのインデックスを検索します

最後に、特定のセルに変更を加える必要がある場合があり、セルインデックスでもこれを行うことができます。

次のコード例は、行のセルのインデックスを取得する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
int cellIndex = row->IndexOf(row->get_Cells()->idx_get(4));

列の操作

Aspose.Wordsドキュメントオブジェクトモデル(DOM)では、TableノードはRowノードとCellノードで構成されます。 したがって、Aspose.WordsのDocumentオブジェクトモデルでは、Word文書のように、列の概念はありません。

設計上、Microsoft WordとAspose.Wordsのテーブル行は完全に独立しており、基本的なプロパティと操作はテーブルの行とセルにのみ含まれています。 これにより、テーブルにいくつかの興味深い属性を持たせることができます:

  • 各テーブルの行には、完全に異なる数のセルを含めることができます
  • 垂直方向には、各行のセルの幅が異なる場合があります
  • 異なる行形式とセル数のテーブルを結合することができます

列に対して実行される操作は、実際には、列に適用されているように見えるように行セルをまとめて変更することによって操作を実行する「ショートカット」です。 つまり、同じテーブル行のセルインデックスを反復処理するだけで、列に対して操作を実行できます。

次のコード例では、テーブルの"列"を構成するセルを収集するファサードクラスを証明することにより、このような操作を簡素化します:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
/// <summary>
/// Represents a facade object for a column of a table in a Microsoft Word document.
/// </summary>
class Column : public System::Object
{
public:
/// <summary>
/// Returns the cells which make up the column.
/// </summary>
ArrayPtr<SharedPtr<Cell>> get_Cells()
{
return GetColumnCells()->ToArray();
}
/// <summary>
/// Returns a new column facade from the table and supplied zero-based index.
/// </summary>
static SharedPtr<WorkingWithTables::Column> FromIndex(SharedPtr<Table> table, int columnIndex)
{
return WorkingWithTables::Column::MakeObject(table, columnIndex);
}
/// <summary>
/// Returns the index of the given cell in the column.
/// </summary>
int IndexOf(SharedPtr<Cell> cell)
{
return GetColumnCells()->IndexOf(cell);
}
/// <summary>
/// Inserts a brand new column before this column into the table.
/// </summary>
SharedPtr<WorkingWithTables::Column> InsertColumnBefore()
{
ArrayPtr<SharedPtr<Cell>> columnCells = get_Cells();
if (columnCells->get_Length() == 0)
{
throw System::ArgumentException(u"Column must not be empty");
}
// Create a clone of this column.
for (SharedPtr<Cell> cell : columnCells)
{
cell->get_ParentRow()->InsertBefore(cell->Clone(false), cell);
}
// This is the new column.
auto column = WorkingWithTables::Column::MakeObject(columnCells[0]->get_ParentRow()->get_ParentTable(), mColumnIndex);
// We want to make sure that the cells are all valid to work with (have at least one paragraph).
for (SharedPtr<Cell> cell : column->get_Cells())
{
cell->EnsureMinimum();
}
// Increase the index which this column represents since there is now one extra column in front.
mColumnIndex++;
return column;
}
/// <summary>
/// Removes the column from the table.
/// </summary>
void Remove()
{
for (SharedPtr<Cell> cell : get_Cells())
{
cell->Remove();
}
}
/// <summary>
/// Returns the text of the column.
/// </summary>
String ToTxt()
{
auto builder = System::MakeObject<System::Text::StringBuilder>();
for (SharedPtr<Cell> cell : get_Cells())
{
builder->Append(cell->ToString(SaveFormat::Text));
}
return builder->ToString();
}
private:
int mColumnIndex;
SharedPtr<Table> mTable;
Column(SharedPtr<Table> table, int columnIndex) : mColumnIndex(0)
{
if (table == nullptr)
{
throw System::ArgumentException(u"table");
}
mTable = table;
mColumnIndex = columnIndex;
}
MEMBER_FUNCTION_MAKE_OBJECT(Column, CODEPORTING_ARGS(SharedPtr<Table> table, int columnIndex), CODEPORTING_ARGS(table, columnIndex));
/// <summary>
/// Provides an up-to-date collection of cells which make up the column represented by this facade.
/// </summary>
SharedPtr<System::Collections::Generic::List<SharedPtr<Cell>>> GetColumnCells()
{
SharedPtr<System::Collections::Generic::List<SharedPtr<Cell>>> columnCells =
System::MakeObject<System::Collections::Generic::List<SharedPtr<Cell>>>();
for (const auto& row : System::IterateOver<Row>(mTable->get_Rows()))
{
SharedPtr<Cell> cell = row->get_Cells()->idx_get(mColumnIndex);
if (cell != nullptr)
{
columnCells->Add(cell);
}
}
return columnCells;
}
};
view raw column-class.h hosted with ❤ by GitHub

次のコード例は、テーブルに空白の列を挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
SharedPtr<WorkingWithTables::Column> column = WorkingWithTables::Column::FromIndex(table, 0);
// Print the plain text of the column to the screen.
std::cout << column->ToTxt() << std::endl;
// Create a new column to the left of this column.
// This is the same as using the "Insert Column Before" command in Microsoft Word.
SharedPtr<WorkingWithTables::Column> newColumn = column->InsertColumnBefore();
for (SharedPtr<Cell> cell : newColumn->get_Cells())
{
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, String(u"Column Text ") + newColumn->IndexOf(cell)));
}

次のコード例は、ドキュメント内のテーブルから列を削除する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 1, true));
SharedPtr<WorkingWithTables::Column> column = WorkingWithTables::Column::FromIndex(table, 2);
column->Remove();
view raw remove-column.h hosted with ❤ by GitHub

行をヘッダー行として指定する

テーブルの最初の行をヘッダー行として最初のページでのみ繰り返すか、テーブルが複数に分割されている場合は各ページで繰り返すかを選択できます。 Aspose.Wordsでは、HeadingFormatプロパティを使用してすべてのページでヘッダー行を繰り返すことができます。

そのような行がテーブルの先頭に次々に配置されている場合は、複数のヘッダー行にマークを付けることもできます。 これを行うには、これらの行にHeadingFormatプロパティを適用する必要があります。

次のコード例は、後続のページで繰り返されるヘッダー行を含むテーブルを作成する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
builder->get_RowFormat()->set_HeadingFormat(true);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->set_Width(100);
builder->InsertCell();
builder->Writeln(u"Heading row 1");
builder->EndRow();
builder->InsertCell();
builder->Writeln(u"Heading row 2");
builder->EndRow();
builder->get_CellFormat()->set_Width(50);
builder->get_ParagraphFormat()->ClearFormatting();
for (int i = 0; i < 50; i++)
{
builder->InsertCell();
builder->get_RowFormat()->set_HeadingFormat(false);
builder->Write(u"Column 1 Text");
builder->InsertCell();
builder->Write(u"Column 2 Text");
builder->EndRow();
}
doc->Save(ArtifactsDir + u"WorkingWithTables.RepeatRowsOnSubsequentPages.docx");

テーブルと行がページ間で破損しないようにする

テーブルの内容をページ間で分割してはならない場合があります。 たとえば、タイトルがテーブルの上にある場合、適切な外観を維持するために、タイトルとテーブルは常に同じページにまとめておく必要があります。

この機能を実現するのに便利な2つの別々の手法があります:

  • Allow row break across pagesは、テーブル行に適用されます
  • Keep with nextは、表のセルの段落に適用されます

デフォルトでは、上記のプロパティは無効になっています。

行がページ{#keep-a-row-from-breaking-across-pages}を越えて破損しないようにする

これには、行のセル内のコンテンツがページ間で分割されないように制限することが含まれます。 Microsoft Wordでは、これはテーブルのプロパティの下に"行をページ間で分割することを許可する"オプションとしてあります。 Aspose.Wordsでは、これはRowRowFormatオブジェクトの下にプロパティRowFormat.AllowBreakAcrossPagesとしてあります。

次のコード例は、テーブル内の各行のページ間で行を分割することを無効にする方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Table spanning two pages.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Disable breaking across pages for all rows in the table.
for (const auto& row : System::IterateOver<Row>(table->get_Rows()))
{
row->get_RowFormat()->set_AllowBreakAcrossPages(false);
}
doc->Save(ArtifactsDir + u"WorkingWithTables.RowFormatDisableBreakAcrossPages.docx");

テーブルがページ間で破壊されないようにする

テーブルがページ間で分割されないようにするには、テーブル内に含まれるコンテンツを一緒に保つように指定する必要があります。

これを行うために、Aspose.Wordsは、ユーザーがテーブルを選択し、テーブルセル内の各段落に対してKeepWithNextパラメータをtrueに有効にするメソッドを使用します。 例外は、テーブルの最後の段落であり、falseに設定する必要があります。

次のコード例は、同じページに一緒に滞在するようにテーブルを設定する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto doc = MakeObject<Document>(MyDir + u"Table spanning two pages.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// We need to enable KeepWithNext for every paragraph in the table to keep it from breaking across a page,
// except for the last paragraphs in the last row of the table.
for (const auto& cell : System::IterateOver<Cell>(table->GetChildNodes(NodeType::Cell, true)))
{
cell->EnsureMinimum();
for (const auto& para : System::IterateOver<Paragraph>(cell->get_Paragraphs()))
{
if (!(cell->get_ParentRow()->get_IsLastRow() && para->get_IsEndOfCell()))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
}
}
doc->Save(ArtifactsDir + u"WorkingWithTables.KeepTableTogether.docx");