Създаване на таблица

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
Клониране на съществуваща таблица Можете да създадете копие на съществуваща таблица, като запазите форматирането на всички редове и клетки Подходящите детски възли трябва да бъдат отстранени, преди таблицата да е готова за употреба