Создайте таблицу
Aspose.Words позволяет пользователям создавать таблицы в документе с нуля и предоставляет несколько различных методов для этого. В этой статье представлены подробные сведения о том, как добавлять отформатированные таблицы в документ, используя каждый из методов, а также сравнение каждого метода в конце статьи.
Стили таблиц по умолчанию
Вновь созданной таблице присваиваются значения по умолчанию, аналогичные тем, которые используются в Microsoft Word:
Single |
|
Black |
|
True |
Создайте таблицу с DocumentBuilder
В Aspose.Words пользователи могут создать таблицу в документе, используя DocumentBuilder. Основной алгоритм создания таблицы следующий:
- Начните таблицу с StartTable
- Добавьте ячейку в таблицу, используя InsertCell – при этом автоматически начнется новая строка
- При необходимости используйте свойство CellFormat, чтобы задать форматирование ячеек
- Вставьте содержимое ячейки, используя соответствующие методы DocumentBuilder, такие как Writeln, InsertImage и другие
- Повторяйте шаги 2-4, пока строка не будет завершена
- Вызовите EndRow, чтобы завершить текущую строку
- При необходимости используйте свойство RowFormat, чтобы задать форматирование строк
- Повторяйте шаги 2-7 до тех пор, пока таблица не будет заполнена
- Вызовите EndTable, чтобы завершить построение таблицы
Важные детали:
- StartTable также может быть вызван внутри ячейки, и в этом случае он запускает создание вложенной таблицы внутри ячейки.
- После вызова InsertCell создается новая ячейка, и любое содержимое, добавленное с помощью других методов класса DocumentBuilder, будет добавлено в текущую ячейку. Чтобы создать новую ячейку в той же строке, снова вызовите InsertCell.
- Если InsertCell вызывается сразу после EndRow и в конце строки, таблица будет продолжена в новой строке.
- Метод EndTable для завершения работы с таблицей следует вызывать только один раз после вызова EndRow. Вызов EndTable перемещает курсор из текущей ячейки в позицию, расположенную сразу за таблицей.
Процесс создания таблицы можно наглядно увидеть на следующем рисунке:
В следующем примере кода показано, как создать простую таблицу, используя DocumentBuilder с форматированием по умолчанию:
// 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); | |
// Start building the table. | |
builder->StartTable(); | |
builder->InsertCell(); | |
builder->Write(u"Row 1, Cell 1 Content."); | |
// Build the second cell. | |
builder->InsertCell(); | |
builder->Write(u"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(u"Row 2, Cell 1 Content"); | |
// Build the second cell. | |
builder->InsertCell(); | |
builder->Write(u"Row 2, Cell 2 Content."); | |
builder->EndRow(); | |
// Signal that we have finished building the table. | |
builder->EndTable(); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.CreateSimpleTable.docx"); |
В следующем примере кода показано, как создать отформатированную таблицу, используя DocumentBuilder:
// 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); | |
SharedPtr<Table> table = builder->StartTable(); | |
builder->InsertCell(); | |
// Table wide formatting must be applied after at least one row is present in the table. | |
table->set_LeftIndent(20.0); | |
// Set height and define the height rule for the header row. | |
builder->get_RowFormat()->set_Height(40.0); | |
builder->get_RowFormat()->set_HeightRule(HeightRule::AtLeast); | |
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::FromArgb(198, 217, 241)); | |
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center); | |
builder->get_Font()->set_Size(16); | |
builder->get_Font()->set_Name(u"Arial"); | |
builder->get_Font()->set_Bold(true); | |
builder->get_CellFormat()->set_Width(100.0); | |
builder->Write(u"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(u"Header Row,\n Cell 2"); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(200.0); | |
builder->Write(u"Header Row,\n Cell 3"); | |
builder->EndRow(); | |
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_White()); | |
builder->get_CellFormat()->set_Width(100.0); | |
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center); | |
// Reset height and define a different height rule for table body. | |
builder->get_RowFormat()->set_Height(30.0); | |
builder->get_RowFormat()->set_HeightRule(HeightRule::Auto); | |
builder->InsertCell(); | |
// Reset font formatting. | |
builder->get_Font()->set_Size(12); | |
builder->get_Font()->set_Bold(false); | |
builder->Write(u"Row 1, Cell 1 Content"); | |
builder->InsertCell(); | |
builder->Write(u"Row 1, Cell 2 Content"); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(200.0); | |
builder->Write(u"Row 1, Cell 3 Content"); | |
builder->EndRow(); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(100.0); | |
builder->Write(u"Row 2, Cell 1 Content"); | |
builder->InsertCell(); | |
builder->Write(u"Row 2, Cell 2 Content"); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(200.0); | |
builder->Write(u"Row 2, Cell 3 Content."); | |
builder->EndRow(); | |
builder->EndTable(); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.FormattedTable.docx"); |
В следующем примере кода показано, как вставить вложенную таблицу, используя DocumentBuilder:
// 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); | |
SharedPtr<Cell> cell = builder->InsertCell(); | |
builder->Writeln(u"Outer Table Cell 1"); | |
builder->InsertCell(); | |
builder->Writeln(u"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->get_FirstParagraph()); | |
// Build the inner table. | |
builder->InsertCell(); | |
builder->Writeln(u"Inner Table Cell 1"); | |
builder->InsertCell(); | |
builder->Writeln(u"Inner Table Cell 2"); | |
builder->EndTable(); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.NestedTable.docx"); |
Создайте таблицу с помощью DOM (объектной модели документа)
Вы можете вставлять таблицы непосредственно в DOM, добавляя новый узел Table в определенном месте.
Пожалуйста, обратите внимание, что сразу после создания узла таблицы сама таблица будет полностью пустой, то есть в ней еще не будет строк и ячеек. Чтобы вставить строки и ячейки в таблицу, добавьте соответствующие дочерние узлы Row и Cell в DOM.
В следующем примере кода показано, как создать новую таблицу с нуля, добавив соответствующие дочерние узлы в дерево документа:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<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. | |
auto table = MakeObject<Table>(doc); | |
doc->get_FirstSection()->get_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. | |
auto row = MakeObject<Row>(doc); | |
row->get_RowFormat()->set_AllowBreakAcrossPages(true); | |
table->AppendChild(row); | |
// We can now apply any auto fit settings. | |
table->AutoFit(AutoFitBehavior::FixedColumnWidths); | |
auto cell = MakeObject<Cell>(doc); | |
cell->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightBlue()); | |
cell->get_CellFormat()->set_Width(80); | |
cell->AppendChild(MakeObject<Paragraph>(doc)); | |
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"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->get_LastCell()->AppendChild(MakeObject<Paragraph>(doc)); | |
row->get_LastCell()->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Row 1, Cell 2 Text")); | |
doc->Save(ArtifactsDir + u"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-C.git. | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
// Note that AutoFitSettings does not apply to tables inserted from HTML. | |
builder->InsertHtml(String(u"<table>") + u"<tr>" + u"<td>Row 1, Cell 1</td>" + u"<td>Row 1, Cell 2</td>" + u"</tr>" + u"<tr>" + | |
u"<td>Row 2, Cell 2</td>" + u"<td>Row 2, Cell 2</td>" + u"</tr>" + u"</table>"); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.InsertTableFromHtml.docx"); |
Вставьте копию существующей таблицы
Часто возникает необходимость создать таблицу на основе уже существующей таблицы в документе. Самый простой способ скопировать таблицу с сохранением всего форматирования - это клонировать узел таблицы, используя метод Clone.
Тот же метод можно использовать для добавления копий существующей строки или ячейки в таблицу.
В следующем примере кода показано, как дублировать таблицу с помощью конструкторов узлов:
// 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)); | |
// Clone the table and insert it into the document after the original. | |
auto tableClone = System::ExplicitCast<Table>(table->Clone(true)); | |
table->get_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->get_ParentNode()->InsertAfter(MakeObject<Paragraph>(doc), table); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.CloneCompleteTable.docx"); |
В следующем примере кода показано, как клонировать последнюю строку таблицы и добавить ее в таблицу:
// 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)); | |
auto clonedRow = System::ExplicitCast<Row>(table->get_LastRow()->Clone(true)); | |
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into. | |
for (const auto& cell : System::IterateOver<Cell>(clonedRow->get_Cells())) | |
{ | |
cell->RemoveAllChildren(); | |
} | |
table->AppendChild(clonedRow); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.CloneLastRow.docx"); |
Если вы планируете создавать таблицы в документе, которые динамически увеличиваются с каждой записью из вашего источника данных, то описанный выше метод не рекомендуется. Вместо этого желаемый результат проще получить, используя Mail merge с регионами. Вы можете узнать больше об этом методе в Mail Merge с регионами раздел.
Сравните способы создания таблицы
Aspose.Words предоставляет несколько методов для создания новых таблиц в документе. Каждый метод имеет свои преимущества и недостатки, поэтому выбор того, какой из них использовать, часто зависит от конкретной ситуации.
Давайте подробнее рассмотрим эти способы создания таблиц и сравним их плюсы и минусы:
Метод | Недостатки |
---|---|
DocumentBuilder |
Стандартный метод вставки таблиц и другого содержимого документа |
Лучше вписывается в окружающий код, который создает и вставляет узлы непосредственно в DOM без использования DocumentBuilder | Таблица создается “пустой”: перед выполнением большинства операций вы должны вызвать EnsureMinimum, чтобы создать все отсутствующие дочерние узлы |
Можно создать новую таблицу из HTML-источника, используя такие теги, как <table> , <tr> , <td> |
|
Вы можете создать копию существующей таблицы, сохранив все форматирование строк и ячеек | Соответствующие дочерние узлы должны быть удалены, прежде чем таблица будет готова к использованию |