Construir una tabla a partir de un DataTable

Contents
[ ]

A menudo, su aplicación extraerá datos de una base de datos y los almacenará en forma de DataTable. Puede insertar fácilmente estos datos en su documento como una nueva tabla y aplicar formato rápidamente a toda la tabla.

Con Aspose.Words, puede recuperar fácilmente datos de una base de datos y almacenarlos como una tabla:

  1. Cree un nuevo objeto DocumentBuilder en su Document.
  2. Inicie una nueva tabla usando DocumentBuilder.
  3. Si queremos insertar los nombres de cada una de las columnas de nuestro DataTable como una fila de encabezado, repita cada columna de datos y escriba los nombres de las columnas en una fila de la tabla.
  4. Repita cada DataRow en el DataTable:
  5. Repita cada objeto en DataRow.
  6. Inserte el objeto en el documento usando DocumentBuilder. El método utilizado depende del tipo de objeto que se inserta, por ejemplo, DocumentBuilder.Writeln para texto y DocumentBuilder.InsertImage para una matriz de bytes que representa una imagen.
  7. Al final del procesamiento del DataRow, también finalice la fila que está creando el DocumentBuilder mediante DocumentBuilder.EndRow.
  8. Una vez que se hayan procesado todas las filas del DataTable, finalice la tabla llamando a DocumentBuilder.EndTable.
  9. Finalmente, podemos configurar el estilo de tabla deseado usando una de las propiedades de tabla apropiadas, como Table.StyleIdentifier, para aplicar formato automáticamente a toda la tabla.

El método ImportTableFromDataTable acepta un objeto DocumentBuilder, el DataTable que contiene los datos y una bandera que especifica si el encabezado de columna del DataTable está incluido en la parte superior de la tabla. Este método crea una tabla a partir de estos parámetros utilizando la posición y el formato actuales del constructor. Proporciona un método para importar datos desde DataTable e insertarlos en una nueva tabla usando DocumentBuilder.

En este ejemplo se utilizan los siguientes datos de nuestro DataTable:

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

El siguiente ejemplo de código muestra cómo ejecutar el algoritmo anterior en 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;
}

Luego, el método se puede invocar fácilmente utilizando su DocumentBuilder y sus datos.

El siguiente ejemplo de código muestra cómo importar los datos de un DataTable e insertarlos en una nueva tabla del documento:

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