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

Contents
[ ]

Часто ваша заявка витягне дані з бази даних і зберігає її у вигляді бази даних DataTableй Ви можете легко вставляти дані в документ, як новий стіл і швидко застосувати форматування на весь стіл.

Використання Aspose.Words, Ви можете легко отримувати дані з бази даних і зберігати його як таблицю:

1,1 км Створити новий DocumentBuilder об’єкт на вашому Documentй 1,1 км Почати новий стіл за допомогою DocumentBuilderй 1,1 км Якщо ми хочемо вставити імена кожного стовпчика з нашого DataTable як рядок заголовка, потім ітерувати через кожен стовпчик даних і написати імена стовпців в ряд в таблиці. 1,1 км Зберігати через кожну DataRow в DataTable:

  1. Встановити по кожному об’єкту DataRowй
  2. Вставте об’єкт в документ, використовуючи DocumentBuilderй Метод, який використовується в залежності від типу об’єкта, який вставляється наприклад DocumentBuilder.Writeln для тексту DocumentBuilder.InsertImage для байтного масиву, який представляє образ.
  3. Наприкінці обробки DataRow також кінець ряду, створеного DocumentBuilder за допомогою DocumentBuilder.EndRowй 1,1 км Як тільки всі рядки з DataTable було оброблено оздоблений стіл за допомогою виклику DocumentBuilder.EndTableй 1,1 км Нарешті ми можемо встановити бажаний стиль таблиці за допомогою одного з відповідних властивостей таблиці, таких як Table.StyleIdentifier автоматично застосувати форматування на весь стіл.

Про нас ImportTableFromDataTable метод приймає DocumentBuilder об’єкт, DataTable що містить дані і прапор, який визначає, якщо заголовок стовпця від DataTable входить у верхній частині столу. Цей метод будує таблицю з цих параметрів, використовуючи позицію будівельника та форматування будівельників. Забезпечує спосіб імпортувати дані з DataTable і вставте його в новий стіл за допомогою DocumentBuilder.

Наші дані DataTable використовується в цьому прикладі:

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

Приклад коду показує, як виконати вище алгоритм в 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;
}

Метод може бути легко викликаний за допомогою вашого DocumentBuilder та дані.

Приклад наступного коду показує, як імпортувати дані з DataTable і вставте його в новий стіл в документі:

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