Створіть таблицю

Aspose.Words дозволяє користувачам створювати таблиці в документі з нуля і надає кілька різних методів для цього. У цій статті наведено детальну інформацію про те, як додати відформатовані таблиці до документа за допомогою кожного з методів, а також порівняння кожного методу в кінці статті.

Стилі таблиць за замовчуванням

Новоствореній таблиці присвоюються значення за замовчуванням, подібні до тих, що використовуються в Microsoft Word:

Властивість таблиці Значення за замовчуванням в Aspose.Words
Border Style Single
Border Width 1/2 пт
Border Color Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

Створіть таблицю з DocumentBuilder

У Aspose.Words користувачі можуть створити таблицю в документі за допомогою DocumentBuilder. Основний алгоритм створення таблиці наступний:

  1. Почніть таблицю з StartTable
  2. Додайте клітинку до таблиці за допомогою InsertCell - це автоматично почне новий рядок
  3. При необхідності використовуйте властивість CellFormat, щоб задати форматування осередків
  4. Вставте вміст комірки, використовуючи відповідні методи DocumentBuilder, такі як Writeln, InsertImage та інші
  5. Повторюйте кроки 2-4, поки рядок не буде завершено
  6. Викличте EndRow, щоб завершити поточний рядок
  7. При необхідності використовуйте властивість RowFormat, щоб задати форматування рядків
  8. Повторюйте кроки 2-7, поки таблиця не буде заповнена
  9. Викличте EndTable, щоб завершити побудову таблиці

Процес створення таблиці можна наочно побачити на наступному малюнку:

creating-table-process

Наступний приклад коду показує, як створити просту таблицю за допомогою 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");
view raw nested-table.h hosted with ❤ by GitHub

Створіть таблицю за допомогою 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 Краще вписується в навколишній код, який створює та вставляє вузли безпосередньо в DOM без використання DocumentBuilder Таблиця створюється “порожньою”: перш ніж виконувати більшість операцій, ви повинні викликати EnsureMinimum, щоб створити всі відсутні дочірні вузли
З HTML Можна створити нову таблицю з джерела HTML, використовуючи такі теги, як <table>, <tr>, <td> Не всі можливі формати таблиць Microsoft Word можна застосувати до HTML
Клонування існуючої таблиці Ви можете створити копію існуючої таблиці, зберігаючи всі форматування рядків і комірок Відповідні дочірні вузли повинні бути видалені, перш ніж таблиця буде готова до використання