Tạo Một Bảng

Aspose.Words cho phép người dùng tạo bảng trong tài liệu từ đầu và cung cấp một số phương pháp khác nhau để làm như vậy. Bài viết này trình bày chi tiết về cách thêm các bảng được định dạng vào tài liệu của bạn bằng từng phương thức, cũng như so sánh từng phương thức ở cuối bài viết.

Kiểu Bảng Mặc Định

Bảng mới được tạo được cung cấp các giá trị mặc định tương tự như các giá trị được sử dụng trong Microsoft Word:

Tài Sản Bảng Mặc định trong Aspose.Words
Border Style Single
Border Width 1/2 hp
Border Color Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

Tạo Một Bảng với DocumentBuilder

Trong Aspose.Words, người dùng có thể tạo một bảng trong tài liệu bằng DocumentBuilder. Thuật toán cơ bản để tạo một bảng như sau:

  1. Bắt đầu bảng với StartTable
  2. Thêm một ô vào bảng bằng cách sử dụng InsertCell – thao tác này sẽ tự động bắt đầu một hàng mới
  3. Tùy chọn, sử dụng thuộc tính CellFormat để chỉ định định dạng ô
  4. Chèn nội dung ô bằng các phương thức DocumentBuilder thích hợp như Writeln, InsertImage và các phương thức khác
  5. Lặp lại các bước 2 -4 cho đến khi hàng hoàn tất
  6. Gọi EndRow để kết thúc hàng hiện tại
  7. Tùy chọn, sử dụng thuộc tính RowFormat để chỉ định định dạng hàng
  8. Lặp lại các bước 2 -7 cho đến khi bảng hoàn tất
  9. Gọi EndTable để hoàn thành việc xây dựng bảng

Quá trình tạo một bảng có thể được nhìn thấy rõ ràng trong hình sau:

creating-table-process

Ví dụ mã sau đây cho thấy cách tạo một bảng đơn giản bằng DocumentBuilder với định dạng mặc định:

// 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");

Ví dụ mã sau đây cho thấy cách tạo bảng được định dạng bằng 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");

Ví dụ mã sau đây cho thấy cách chèn bảng lồng nhau bằng 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

Tạo Một Bảng thông qua DOM (Mô Hình Đối tượng Tài liệu)

Bạn có thể chèn các bảng trực tiếp vào DOM bằng cách thêm nút Table mới tại một vị trí cụ thể.

Xin lưu ý rằng ngay sau khi tạo nút bảng, bản thân bảng sẽ hoàn toàn trống, nghĩa là nó chưa chứa các hàng và ô. Để chèn các hàng và ô vào bảng, hãy thêm các nút con RowCell thích hợp vào DOM.

Ví dụ mã sau đây cho thấy cách xây dựng một bảng mới từ đầu bằng cách thêm các nút con thích hợp vào cây tài liệu:

// 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");

Tạo Một Bảng từ HTML

Aspose.Words hỗ trợ chèn nội dung vào tài liệu từ nguồn HTML bằng phương thức InsertHtml. Đầu vào có thể là một trang HTML hoàn chỉnh hoặc chỉ là một đoạn mã một phần.

Sử dụng phương thức InsertHtml, người dùng có thể chèn các bảng vào tài liệu thông qua các thẻ bảng như <table>, <tr>, <td>.

Ví dụ mã sau đây cho thấy cách chèn một bảng vào tài liệu từ một chuỗi chứa HTML thẻ:

// 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");

Chèn Một Bản Sao Của Một Bảng Hiện Có

Thường có những lúc bạn cần tạo một bảng dựa trên một bảng đã có trong tài liệu. Cách dễ nhất để sao chép một bảng trong khi giữ lại tất cả các định dạng là sao chép Nút Bảng bằng phương thức Clone.

Kỹ thuật tương tự có thể được sử dụng để thêm các bản sao của một hàng hoặc ô hiện có vào bảng.

Ví dụ mã sau đây cho thấy cách sao chép bảng bằng cách sử dụng hàm tạo nút:

// 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");

Ví dụ mã sau đây cho thấy cách sao chép hàng cuối cùng của bảng và nối nó vào bảng:

// 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");

Nếu bạn đang xem xét việc tạo các bảng trong một tài liệu phát triển linh hoạt với mỗi bản ghi từ nguồn dữ liệu của bạn, thì phương pháp trên không được khuyến khích. Thay vào đó, đầu ra mong muốn dễ dàng đạt được hơn bằng cách sử dụng Mail merge với các vùng. Bạn có thể tìm hiểu thêm về kỹ thuật này trong Mail Merge Với Các Khu Vực phần.

So Sánh Các Cách Để Tạo Bảng

Aspose.Words cung cấp một số phương pháp để tạo bảng mới trong tài liệu. Mỗi phương pháp đều có những ưu điểm và nhược điểm riêng, vì vậy việc lựa chọn sử dụng phương pháp nào thường phụ thuộc vào tình huống cụ thể.

Chúng ta hãy xem xét kỹ hơn những cách tạo bảng này và so sánh ưu và nhược điểm của chúng:

Phương pháp Ưu điểm Nhược điểm
DocumentBuilder Phương pháp tiêu chuẩn để chèn bảng và nội dung tài liệu khác Đôi khi rất khó để tạo ra nhiều loại bảng cùng một lúc với cùng một ví dụ xây dựng
Qua DOM Phù hợp hơn với mã xung quanh tạo và chèn các nút trực tiếp vào DOM mà không cần sử dụng DocumentBuilder Bảng được tạo “trống”: trước khi thực hiện hầu hết các thao tác, bạn phải gọi EnsureMinimum để tạo bất kỳ nút con nào bị thiếu
Từ HTML Có thể tạo một bảng mới từ nguồn HTML bằng cách sử dụng các thẻ như <table>, <tr>, <td> Không phải tất cả các định dạng bảng Microsoft Word có thể được áp dụng cho HTML
Nhân bản một bảng hiện có Bạn có thể tạo một bản sao của một bảng hiện có trong khi vẫn giữ nguyên tất cả định dạng hàng và ô Các nút con thích hợp phải được xóa trước khi bảng sẵn sàng để sử dụng