Xây dựng bảng từ DataTable

Contents
[ ]

Thông thường, ứng dụng của bạn sẽ lấy dữ liệu từ cơ sở dữ liệu và lưu trữ dưới dạng DataTable. Bạn có thể dễ dàng chèn dữ liệu này vào tài liệu của mình dưới dạng bảng mới và nhanh chóng áp dụng định dạng cho toàn bộ bảng.

Sử dụng Aspose.Words, bạn có thể dễ dàng truy xuất dữ liệu từ cơ sở dữ liệu và lưu trữ dưới dạng bảng:

  1. Tạo đối tượng DocumentBuilder mới trên Document của bạn.
  2. Bắt đầu một bảng mới bằng DocumentBuilder.
  3. Nếu chúng ta muốn chèn tên của từng cột từ DataTable làm hàng tiêu đề, sau đó lặp qua từng cột dữ liệu và viết tên cột vào một hàng trong bảng.
  4. Lặp lại qua từng DataRow trong DataTable:
    1. Lặp lại từng đối tượng trong DataRow.
    2. Chèn đối tượng vào tài liệu bằng DocumentBuilder. Phương thức được sử dụng tùy thuộc vào loại đối tượng được chèn, ví dụ DocumentBuilder.Writeln cho văn bản và DocumentBuilder.InsertImage cho mảng byte đại diện cho hình ảnh.
    3. Khi kết thúc quá trình xử lý DataRow, hàng được DocumentBuilder tạo bằng cách sử dụng DocumentBuilder.EndRow cũng kết thúc.
  5. Khi tất cả các hàng từ DataTable đã được xử lý, hãy hoàn tất bảng bằng cách gọi DocumentBuilder.EndTable.
  6. Cuối cùng, chúng ta có thể đặt kiểu bảng mong muốn bằng cách sử dụng một trong các thuộc tính bảng thích hợp như Table.StyleIdentifier để tự động áp dụng định dạng cho toàn bộ bảng.

Phương thức ImportTableFromDataTable chấp nhận một đối tượng DocumentBuilder, DataTable chứa dữ liệu và một cờ xác định xem tiêu đề cột từ DataTable có được đưa vào đầu bảng hay không. Phương pháp này xây dựng một bảng từ các tham số này bằng cách sử dụng vị trí và định dạng hiện tại của trình tạo. Cung cấp phương thức nhập dữ liệu từ DataTable và chèn dữ liệu đó vào bảng mới bằng DocumentBuilder.

Dữ liệu sau trong DataTable của chúng tôi được sử dụng trong ví dụ này:

how-to-build-a-table-from-a-datatable-aspose-words-net

Ví dụ mã sau đây cho thấy cách thực thi thuật toán trên trong Aspose.Words:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
/// <summary>
/// Imports the content from the specified DataTable into a new Aspose.Words Table object.
/// The table is inserted at the document builder's current position and using the current builder's formatting if any is defined.
/// </summary>
public Table ImportTableFromDataTable(DocumentBuilder builder, DataTable dataTable,
bool importColumnHeadings)
{
Table table = builder.StartTable();
// Check if the columns' names from the data source are to be included in a header row.
if (importColumnHeadings)
{
// Store the original values of these properties before changing them.
bool boldValue = builder.Font.Bold;
ParagraphAlignment paragraphAlignmentValue = builder.ParagraphFormat.Alignment;
// Format the heading row with the appropriate properties.
builder.Font.Bold = true;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// Create a new row and insert the name of each column into the first row of the table.
foreach (DataColumn column in dataTable.Columns)
{
builder.InsertCell();
builder.Writeln(column.ColumnName);
}
builder.EndRow();
// Restore the original formatting.
builder.Font.Bold = boldValue;
builder.ParagraphFormat.Alignment = paragraphAlignmentValue;
}
foreach (DataRow dataRow in dataTable.Rows)
{
foreach (object item in dataRow.ItemArray)
{
// Insert a new cell for each object.
builder.InsertCell();
switch (item.GetType().Name)
{
case "DateTime":
// Define a custom format for dates and times.
DateTime dateTime = (DateTime) item;
builder.Write(dateTime.ToString("MMMM d, yyyy"));
break;
default:
// By default any other item will be inserted as text.
builder.Write(item.ToString());
break;
}
}
// After we insert all the data from the current record, we can end the table row.
builder.EndRow();
}
// We have finished inserting all the data from the DataTable, we can end the table.
builder.EndTable();
return table;
}

Sau đó, bạn có thể dễ dàng gọi phương thức này bằng cách sử dụng DocumentBuilder và dữ liệu của mình.

Ví dụ về mã sau đây cho biết cách nhập dữ liệu từ DataTable và chèn dữ liệu đó vào bảng mới trong tài liệu:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
// We can position where we want the table to be inserted and specify any extra formatting to the table.
DocumentBuilder builder = new DocumentBuilder(doc);
// We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape;
DataSet ds = new DataSet();
ds.ReadXml(MyDir + "List of people.xml");
// Retrieve the data from our data source, which is stored as a DataTable.
DataTable dataTable = ds.Tables[0];
// Build a table in the document from the data contained in the DataTable.
Table table = ImportTableFromDataTable(builder, dataTable, true);
// We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1;
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn;
// For our table, we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren();
doc.Save(ArtifactsDir + "WorkingWithTables.BuildTableFromDataTable.docx");