Изграждане на таблица от DataTable
Често вашето приложение ще изтегли данни от база данни и ще го съхранява под формата на DataTable. Можете лесно да въведете тези данни във вашия документ като нова таблица и бързо да приложите форматиране на цялата таблица.
Използване Aspose.Words, лесно можете да извлечете данни от база данни и да ги съхранявате като таблица:
- Създаване на нов DocumentBuilder Възразявам. Document.
- Създаване на нова таблица с помощта на DocumentBuilder.
- Ако искаме да вмъкнем имената на всяка от колоните от нашите DataTable като заглавен ред след това итерат през всяка колона данни и напишете имената на колоните в ред в таблицата.
- Итерат през всеки DataRow в DataTable:
- Итерат през всеки обект в DataRow.
- Въведете обекта в документа, като използвате DocumentBuilder. Използваният метод зависи от вида на обекта, който се вмъква, например DocumentBuilder.Writeln за текст и DocumentBuilder.InsertImage за байт масив, който представлява изображение.
- В края на обработката DataRow Също така край на реда, създаден от DocumentBuilder чрез DocumentBuilder.EndRow.
- След като всички редове от DataTable Бяха обработени довършвайки таблицата с обаждане DocumentBuilder.EndTable.
- Накрая можем да зададете желания стил таблица с помощта на един от подходящите свойства таблица като Table.StyleIdentifier автоматично да се прилага форматиране на цялата таблица.
На ImportTableFromDataTable метод приема DocumentBuilder обект, DataTable съдържащ данните и флаг, който посочва дали заглавието на колоната от DataTable са включени в горната част на масата. Този метод изгражда таблица от тези параметри, използвайки текущата позиция и форматирането на сградата. Предоставя метод за внос на данни от DataTable
и да го поставите в нова таблица с помощта на DocumentBuilder.
Следните данни в нашия DataTable се използва в този пример:
Следният пример за код показва как да се изпълни горния алгоритъм в 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 и данни.
Следният пример за код показва как да се внасят данните от a 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"); |