Создайте стол
Aspose.Words Это позволяет пользователям создавать таблицы в документе с нуля и предоставляет несколько различных методов для этого. В этой статье представлена подробная информация о том, как добавить отформатированные таблицы в ваш документ с использованием каждого метода, а также сравнение каждого метода в конце статьи.
По умолчанию Table Styles
Вновь созданной таблице приведены значения по умолчанию, аналогичные тем, которые используются в Microsoft Word:
Настольная собственность | Дефолт в Aspose.Words |
---|---|
Border Style |
Single |
Border Width |
1/2 pt |
Border Color |
Black |
Left and Right Padding |
5.4 pts |
AutoFit Mode |
AutoFit to Window |
Allow AutoFit |
True |
Создайте таблицу с документостроителем
В Aspose.Words, Пользователи могут создать таблицу в документе, используя DocumentBuilder. Основной алгоритм создания таблицы выглядит следующим образом:
- Начните стол с StartTable
- Добавьте ячейку в стол, используя InsertCell Это автоматически запускает новый ряд
- По желанию используйте CellFormat свойство определять форматирование ячеек
- Вставьте содержимое ячейки, используя соответствующую DocumentBuilder Такие методы, как Writeln, InsertImage, и другие
- Повторять шаги 2-4 до завершения строки
- Звони. EndRow Чтобы закончить текущий ряд
- По желанию используйте RowFormat свойство указывать форматирование строк
- Повторите шаги 2-7, пока таблица не будет завершена
- Звони. EndTable Чтобы закончить строительство стола
Важные детали:
- StartTable Его также можно назвать внутри клетки, и в этом случае он начинает создание вложенного стола внутри клетки.
- После звонка InsertCell, создается новая ячейка и любой контент, который вы добавляете, используя другие методы DocumentBuilder Класс будет добавлен к текущей ячейке. Чтобы создать новую ячейку в том же ряду, позвоните InsertCell Опять.
- Если InsertCell Называется сразу после EndRow В конце строки стол продолжится на новой строке.
- The EndTable Способ окончания таблицы следует вызывать только один раз после вызова EndRow. Звонить EndTable перемещает курсор из текущей ячейки в положение сразу после стола.
Процесс создания таблицы можно четко увидеть на следующей картинке:
Следующий пример кода показывает, как создать простую таблицу. DocumentBuilder с форматированием по умолчанию:
// 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); | |
// Start building the table. | |
builder.StartTable(); | |
builder.InsertCell(); | |
builder.Write("Row 1, Cell 1 Content."); | |
// Build the second cell. | |
builder.InsertCell(); | |
builder.Write("Row 1, Cell 2 Content."); | |
// Call the following method to end the row and start a new row. | |
builder.EndRow(); | |
// Build the first cell of the second row. | |
builder.InsertCell(); | |
builder.Write("Row 2, Cell 1 Content"); | |
// Build the second cell. | |
builder.InsertCell(); | |
builder.Write("Row 2, Cell 2 Content."); | |
builder.EndRow(); | |
// Signal that we have finished building the table. | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx"); |
Следующий пример кода показывает, как создать отформатированную таблицу с помощью DocumentBuilder:
// 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); | |
Table table = builder.StartTable(); | |
builder.InsertCell(); | |
// Table wide formatting must be applied after at least one row is present in the table. | |
table.LeftIndent = 20.0; | |
// Set height and define the height rule for the header row. | |
builder.RowFormat.Height = 40.0; | |
builder.RowFormat.HeightRule = HeightRule.AtLeast; | |
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241); | |
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; | |
builder.Font.Size = 16; | |
builder.Font.Name = "Arial"; | |
builder.Font.Bold = true; | |
builder.CellFormat.Width = 100.0; | |
builder.Write("Header Row,\n Cell 1"); | |
// We don't need to specify this cell's width because it's inherited from the previous cell. | |
builder.InsertCell(); | |
builder.Write("Header Row,\n Cell 2"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Header Row,\n Cell 3"); | |
builder.EndRow(); | |
builder.CellFormat.Shading.BackgroundPatternColor = Color.White; | |
builder.CellFormat.Width = 100.0; | |
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; | |
// Reset height and define a different height rule for table body. | |
builder.RowFormat.Height = 30.0; | |
builder.RowFormat.HeightRule = HeightRule.Auto; | |
builder.InsertCell(); | |
// Reset font formatting. | |
builder.Font.Size = 12; | |
builder.Font.Bold = false; | |
builder.Write("Row 1, Cell 1 Content"); | |
builder.InsertCell(); | |
builder.Write("Row 1, Cell 2 Content"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Row 1, Cell 3 Content"); | |
builder.EndRow(); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 100.0; | |
builder.Write("Row 2, Cell 1 Content"); | |
builder.InsertCell(); | |
builder.Write("Row 2, Cell 2 Content"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Row 2, Cell 3 Content."); | |
builder.EndRow(); | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx"); |
Следующий пример кода показывает, как вставить вложенную таблицу с помощью DocumentBuilder:
// 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); | |
Cell cell = builder.InsertCell(); | |
builder.Writeln("Outer Table Cell 1"); | |
builder.InsertCell(); | |
builder.Writeln("Outer Table Cell 2"); | |
// This call is important to create a nested table within the first table. | |
// Without this call, the cells inserted below will be appended to the outer table. | |
builder.EndTable(); | |
// Move to the first cell of the outer table. | |
builder.MoveTo(cell.FirstParagraph); | |
// Build the inner table. | |
builder.InsertCell(); | |
builder.Writeln("Inner Table Cell 1"); | |
builder.InsertCell(); | |
builder.Writeln("Inner Table Cell 2"); | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx"); |
Создайте стол через DOM ()Document Object Model)
Вы можете вставлять таблицы непосредственно в DOM Добавляя новый Table Узел в определенной позиции.
Обратите внимание, что сразу после создания столового узла сам стол будет полностью пустым, то есть он еще не содержит строк и ячеек. Чтобы вставить строки и ячейки в таблицу, добавьте соответствующие Row и Cell Детские узлы в DOM.
Следующий пример кода показывает, как построить новую таблицу с нуля, добавив соответствующие узлы ребенка в дерево документов:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
// We start by creating the table object. Note that we must pass the document object | |
// to the constructor of each node. This is because every node we create must belong | |
// to some document. | |
Table table = new Table(doc); | |
doc.FirstSection.Body.AppendChild(table); | |
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used | |
// to ensure that the specified node is valid. In this case, a valid table should have at least one Row and one cell. | |
// Instead, we will handle creating the row and table ourselves. | |
// This would be the best way to do this if we were creating a table inside an algorithm. | |
Row row = new Row(doc); | |
row.RowFormat.AllowBreakAcrossPages = true; | |
table.AppendChild(row); | |
Cell cell = new Cell(doc); | |
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue; | |
cell.CellFormat.Width = 80; | |
cell.AppendChild(new Paragraph(doc)); | |
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text")); | |
row.AppendChild(cell); | |
// We would then repeat the process for the other cells and rows in the table. | |
// We can also speed things up by cloning existing cells and rows. | |
row.AppendChild(cell.Clone(false)); | |
row.LastCell.AppendChild(new Paragraph(doc)); | |
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text")); | |
// We can now apply any auto fit settings. | |
table.AutoFit(AutoFitBehavior.FixedColumnWidths); | |
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx"); |
Создайте таблицу из HTML
Aspose.Words поддерживает вставку контента в документ из источника HTML с использованием InsertHtml метод. Ввод может быть полной HTML-страницей или просто частичным фрагментом.
Используя InsertHtml метод, пользователи могут вставлять таблицы в документ с помощью тегов таблицы, таких как <table>
, <tr>
, <td>
.
Следующий пример кода показывает, как вставить таблицу в документ из строки, содержащей теги HTML:
// 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); | |
// Note that AutoFitSettings does not apply to tables inserted from HTML. | |
builder.InsertHtml("<table>" + | |
"<tr>" + | |
"<td>Row 1, Cell 1</td>" + | |
"<td>Row 1, Cell 2</td>" + | |
"</tr>" + | |
"<tr>" + | |
"<td>Row 2, Cell 2</td>" + | |
"<td>Row 2, Cell 2</td>" + | |
"</tr>" + | |
"</table>"); | |
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx"); |
Вставить копию существующего стола
Нередко возникает необходимость создания таблицы на основе уже существующей таблицы в документе. Самый простой способ дублировать таблицу, сохраняя при этом все форматирование, - это клонировать узел таблицы с помощью Clone метод.
Этот же метод можно использовать для добавления копий существующей строки или ячейки в таблицу.
Следующий пример кода показывает, как дублировать таблицу с помощью конструкторов узлов:
// 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); | |
// Clone the table and insert it into the document after the original. | |
Table tableClone = (Table) table.Clone(true); | |
table.ParentNode.InsertAfter(tableClone, table); | |
// Insert an empty paragraph between the two tables, | |
// or else they will be combined into one upon saving this has to do with document validation. | |
table.ParentNode.InsertAfter(new Paragraph(doc), table); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx"); |
Следующий пример кода показывает, как клонировать последнюю строку таблицы и добавить ее к таблице:
// 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); | |
Row clonedRow = (Row) table.LastRow.Clone(true); | |
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into. | |
foreach (Cell cell in clonedRow.Cells) | |
cell.RemoveAllChildren(); | |
table.AppendChild(clonedRow); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx"); |
Если вы смотрите на создание таблиц в документе, которые динамически растут с каждой записью из вашего источника данных, то вышеупомянутый метод не рекомендуется. Вместо этого желаемый результат легче достигается с помощью Mail merge с регионами. Вы можете узнать больше об этой технике в Mail Merge с регионами Раздел.
Сравните способы создания таблицы
Aspose.Words Предоставляет несколько способов создания новых таблиц в документе. Каждый метод имеет свои преимущества и недостатки, поэтому выбор того, какой из них использовать, часто зависит от конкретной ситуации.
Давайте более подробно рассмотрим эти способы создания таблиц и сравним их плюсы и минусы:
метод | Преимущества | Недостатки |
---|---|---|
Виа DocumentBuilder |
Стандартный метод вставки таблиц и другого содержания документов | Иногда трудно создать много разновидностей таблиц одновременно с одним и тем же экземпляром конструктора |
Виа DOM | Лучше подходит с окружающим кодом, который создает и вставляет узлы непосредственно в DOM Без использования a DocumentBuilder | Таблица создается “пустой”: перед выполнением большинства операций необходимо позвонить EnsureMinimum Создание любых недостающих узлов ребенка |
Из HTML | Может создать новую таблицу из HTML-источника с помощью тегов, таких как: <table> , <tr> , <td> |
Не все возможно Microsoft Word Форматы таблиц могут быть применены к HTML |
Клонирование существующего стола | Вы можете создать копию существующей таблицы, сохраняя при этом форматирование всех строк и ячеек | Соответствующие детские узлы должны быть удалены до того, как стол будет готов к использованию |