Работа с колоннами и рядами

Чтобы лучше контролировать работу таблиц, научитесь манипулировать столбцами и строками.

Найдите индекс элементов таблицы

Колонки, строки и ячейки управляются путем доступа к выбранному узлу документа по его индексу. Поиск индекса любого узла включает в себя сбор всех дочерних узлов типа элемента из родительского узла, а затем использование IndexOf Способ нахождения индекса нужного узла в коллекции.

Найдите индекс таблицы в документе

Иногда вам может потребоваться внести изменения в определенную таблицу в документе. Для этого можно обратиться к таблице по ее индексу.

Следующий пример кода показывает, как восстановить индекс таблицы в документе:

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

Найдите индекс строки в таблице

Точно так же вам может потребоваться внести изменения в определенную строку в выбранной таблице. Для этого также можно обратиться к строке по ее индексу.

Следующий пример кода показывает, как извлечь индекс строки в таблице:

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

Найти индекс клетки в ряде

Наконец, вам может потребоваться внести изменения в конкретную клетку, и вы можете сделать это по индексу клетки.

Следующий пример кода показывает, как получить индекс ячейки подряд:

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

Работа с колоннами

В этом Aspose.Words Document Object Model ()DOM), Table Узел состоит из Row узлы и затем Cell Узлы. Таким образом, в Document Объектная модель Aspose.WordsКак и в документах Word, понятие столбца отсутствует.

По дизайну, стол в ряд Microsoft Word и Aspose.Words Они полностью независимы, а основные свойства и операции содержатся только в строках и ячейках таблицы. Это дает таблицам возможность иметь некоторые интересные атрибуты:

  • Каждая строка таблицы может иметь совершенно разное количество ячеек
  • Вертикально, ячейки каждого ряда могут иметь разную ширину
  • Можно объединять таблицы с различными форматами строк и количеством ячеек

Любые операции, выполняемые на столбцах, на самом деле являются “короткими”, которые выполняют операцию путем коллективного изменения ячеек строк таким образом, что кажется, что они применяются к столбцам. То есть, вы можете выполнять операции на столбцах, просто повторяя один и тот же индекс ячеек строки таблицы.

Следующий пример кода упрощает такие операции, доказывая класс фасада, который собирает ячейки, составляющие “столбец” таблицы:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
/// <summary>
/// Represents a facade object for a column of a table in a Microsoft Word document.
/// </summary>
internal class Column
{
private Column(Table table, int columnIndex)
{
mTable = table ?? throw new ArgumentException("table");
mColumnIndex = columnIndex;
}
/// <summary>
/// Returns a new column facade from the table and supplied zero-based index.
/// </summary>
public static Column FromIndex(Table table, int columnIndex)
{
return new Column(table, columnIndex);
}
/// <summary>
/// Returns the cells which make up the column.
/// </summary>
public Cell[] Cells => GetColumnCells().ToArray();
/// <summary>
/// Returns the index of the given cell in the column.
/// </summary>
public int IndexOf(Cell cell)
{
return GetColumnCells().IndexOf(cell);
}
/// <summary>
/// Inserts a brand new column before this column into the table.
/// </summary>
public Column InsertColumnBefore()
{
Cell[] columnCells = Cells;
if (columnCells.Length == 0)
throw new ArgumentException("Column must not be empty");
// Create a clone of this column.
foreach (Cell cell in columnCells)
cell.ParentRow.InsertBefore(cell.Clone(false), cell);
// This is the new column.
Column column = new Column(columnCells[0].ParentRow.ParentTable, mColumnIndex);
// We want to make sure that the cells are all valid to work with (have at least one paragraph).
foreach (Cell cell in column.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>
public void Remove()
{
foreach (Cell cell in Cells)
cell.Remove();
}
/// <summary>
/// Returns the text of the column.
/// </summary>
public string ToTxt()
{
StringBuilder builder = new StringBuilder();
foreach (Cell cell in Cells)
builder.Append(cell.ToString(SaveFormat.Text));
return builder.ToString();
}
/// <summary>
/// Provides an up-to-date collection of cells which make up the column represented by this facade.
/// </summary>
private List<Cell> GetColumnCells()
{
List<Cell> columnCells = new List<Cell>();
foreach (Row row in mTable.Rows)
{
Cell cell = row.Cells[mColumnIndex];
if (cell != null)
columnCells.Add(cell);
}
return columnCells;
}
private int mColumnIndex;
private readonly Table mTable;
}
view raw column-class.cs hosted with ❤ by GitHub

Следующий пример кода показывает, как вставить пустую колонку в таблицу:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Column column = Column.FromIndex(table, 0);
// Print the plain text of the column to the screen.
Console.WriteLine(column.ToTxt());
// Create a new column to the left of this column.
// This is the same as using the "Insert Column Before" command in Microsoft Word.
Column newColumn = column.InsertColumnBefore();
foreach (Cell cell in newColumn.Cells)
cell.FirstParagraph.AppendChild(new Run(doc, "Column Text " + newColumn.IndexOf(cell)));

Следующий пример кода показывает, как удалить колонку из таблицы в документе:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 1, true);
Column column = Column.FromIndex(table, 2);
column.Remove();

Укажите Rows как Header Rows

Вы можете повторить первую строку в таблице в виде заголовка только на первой странице или на каждой странице, если таблица разделена на несколько. в Aspose.Words, Вы можете повторить строку заголовка на каждой странице, используя HeadingFormat собственность.

Вы также можете отметить несколько рядов заголовков, если такие ряды расположены один за другим в начале таблицы. Для этого вам необходимо применить HeadingFormat Свойства этих рядов.

Следующий пример кода показывает, как построить таблицу, которая включает строки заголовков, которые повторяются на последующих страницах:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartTable();
builder.RowFormat.HeadingFormat = true;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.CellFormat.Width = 100;
builder.InsertCell();
builder.Writeln("Heading row 1");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Heading row 2");
builder.EndRow();
builder.CellFormat.Width = 50;
builder.ParagraphFormat.ClearFormatting();
for (int i = 0; i < 50; i++)
{
builder.InsertCell();
builder.RowFormat.HeadingFormat = false;
builder.Write("Column 1 Text");
builder.InsertCell();
builder.Write("Column 2 Text");
builder.EndRow();
}
doc.Save(ArtifactsDir + "WorkingWithTables.RepeatRowsOnSubsequentPages.docx");

Держите столы и ряды от прорыва через страницы

Бывают случаи, когда содержимое таблицы не должно быть разделено на страницы. Например, если заголовок находится над таблицей, заголовок и таблица всегда должны храниться вместе на одной странице, чтобы сохранить правильный внешний вид.

Есть два отдельных метода, которые полезны для достижения этой функциональности:

  • Allow row break across pages, который применяется к столовым рядам
  • Keep with next, который применяется к абзацам в ячейках таблицы

По умолчанию вышеперечисленные свойства отключены.

Держите ряд от прорыва через страницы

Это включает в себя ограничение содержимого внутри ячеек строки от деления на страницу. в Microsoft Word, Это можно найти в разделе Свойства таблицы в качестве опции “Разрешить строку разбивать страницы”. в Aspose.Words Он находится под RowFormat объектом Row как имущество RowFormat.AllowBreakAcrossPages.

Следующий пример кода показывает, как отключить разбивку строк на страницах для каждой строки в таблице:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Table spanning two pages.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
// Disable breaking across pages for all rows in the table.
foreach (Row row in table.Rows)
row.RowFormat.AllowBreakAcrossPages = false;
doc.Save(ArtifactsDir + "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-.NET.git.
Document doc = new Document(MyDir + "Table spanning two pages.docx");
Table table = (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.
foreach (Cell cell in table.GetChildNodes(NodeType.Cell, true))
{
cell.EnsureMinimum();
foreach (Paragraph para in cell.Paragraphs)
if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
para.ParagraphFormat.KeepWithNext = true;
}
doc.Save(ArtifactsDir + "WorkingWithTables.KeepTableTogether.docx");