Crear una tabla
Aspose.Words permite a los usuarios crear tablas en un documento desde cero y proporciona varios métodos diferentes para hacerlo. Este artículo presenta detalles sobre cómo agregar tablas formateadas a su documento usando cada método, así como una comparación de cada método al final del artículo.
Estilos de tabla predeterminados
La tabla recién creada recibe valores predeterminados similares a los utilizados en Microsoft Word:
Propiedad de tabla | Predeterminado en Aspose.Words |
---|---|
Border Style |
Single |
Border Width |
1/2 pt |
Border Color |
Black |
Left and Right Padding |
5.4 pts |
AutoFit Mode |
AutoFit to Window |
Allow AutoFit |
True |
Crear una tabla con DocumentBuilder
En Aspose.Words, los usuarios pueden crear una tabla en un documento usando DocumentBuilder. El algoritmo básico para crear una tabla es el siguiente:
- Iniciar la mesa con StartTable
- Agregue una celda a la tabla usando InsertCell; esto inicia automáticamente una nueva fila
- Opcionalmente, use la propiedad CellFormat para especificar el formato de celda.
- Inserte el contenido de la celda utilizando los métodos DocumentBuilder apropiados, como Writeln, InsertImage y otros.
- Repita los pasos 2 a 4 hasta completar la fila.
- Llame a EndRow para finalizar la fila actual.
- Opcionalmente, use la propiedad RowFormat para especificar el formato de fila.
- Repita los pasos 2-7 hasta que la tabla esté completa.
- Llame a EndTable para terminar de construir la mesa.
Detalles importantes:
- StartTable también se puede llamar dentro de una celda, en cuyo caso inicia la creación de una tabla anidada dentro de la celda.
- Después de llamar a InsertCell, se crea una nueva celda y cualquier contenido que agregue utilizando otros métodos de la clase DocumentBuilder se agregará a la celda actual. Para crear una nueva celda en la misma fila, llame a InsertCell nuevamente.
- Si se llama a InsertCell inmediatamente después de EndRow y al final de una fila, la tabla continuará en una nueva fila.
- El método EndTable para finalizar la tabla solo debe llamarse una vez después de llamar a EndRow. Al llamar a EndTable se mueve el cursor desde la celda actual a la posición inmediatamente después de la tabla.
El proceso de creación de una tabla se puede ver claramente en la siguiente imagen:
El siguiente ejemplo de código muestra cómo crear una tabla simple usando DocumentBuilder con formato predeterminado:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Start building the table. | |
builder.StartTable(); | |
builder.InsertCell(); | |
builder.Write("Row 1, Cell 1 Content."); | |
// Build the second cell. | |
builder.InsertCell(); | |
builder.Write("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("Row 2, Cell 1 Content"); | |
// Build the second cell. | |
builder.InsertCell(); | |
builder.Write("Row 2, Cell 2 Content."); | |
builder.EndRow(); | |
// Signal that we have finished building the table. | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx"); |
El siguiente ejemplo de código muestra cómo crear una tabla formateada usando DocumentBuilder:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Table table = builder.StartTable(); | |
builder.InsertCell(); | |
// Table wide formatting must be applied after at least one row is present in the table. | |
table.LeftIndent = 20.0; | |
// Set height and define the height rule for the header row. | |
builder.RowFormat.Height = 40.0; | |
builder.RowFormat.HeightRule = HeightRule.AtLeast; | |
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241); | |
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; | |
builder.Font.Size = 16; | |
builder.Font.Name = "Arial"; | |
builder.Font.Bold = true; | |
builder.CellFormat.Width = 100.0; | |
builder.Write("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("Header Row,\n Cell 2"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Header Row,\n Cell 3"); | |
builder.EndRow(); | |
builder.CellFormat.Shading.BackgroundPatternColor = Color.White; | |
builder.CellFormat.Width = 100.0; | |
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; | |
// Reset height and define a different height rule for table body. | |
builder.RowFormat.Height = 30.0; | |
builder.RowFormat.HeightRule = HeightRule.Auto; | |
builder.InsertCell(); | |
// Reset font formatting. | |
builder.Font.Size = 12; | |
builder.Font.Bold = false; | |
builder.Write("Row 1, Cell 1 Content"); | |
builder.InsertCell(); | |
builder.Write("Row 1, Cell 2 Content"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Row 1, Cell 3 Content"); | |
builder.EndRow(); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 100.0; | |
builder.Write("Row 2, Cell 1 Content"); | |
builder.InsertCell(); | |
builder.Write("Row 2, Cell 2 Content"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Row 2, Cell 3 Content."); | |
builder.EndRow(); | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx"); |
El siguiente ejemplo de código muestra cómo insertar una tabla anidada usando DocumentBuilder:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Cell cell = builder.InsertCell(); | |
builder.Writeln("Outer Table Cell 1"); | |
builder.InsertCell(); | |
builder.Writeln("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.FirstParagraph); | |
// Build the inner table. | |
builder.InsertCell(); | |
builder.Writeln("Inner Table Cell 1"); | |
builder.InsertCell(); | |
builder.Writeln("Inner Table Cell 2"); | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx"); |
Crear una tabla a través de DOM (modelo de objetos de documento)
Puede insertar tablas directamente en DOM agregando un nuevo nodo Table en una posición específica.
Tenga en cuenta que inmediatamente después de la creación del nodo de la tabla, la tabla en sí estará completamente vacía, es decir, aún no contiene filas ni celdas. Para insertar filas y celdas en una tabla, agregue los nodos secundarios Row y Cell apropiados al DOM.
El siguiente ejemplo de código muestra cómo crear una nueva tabla desde cero agregando los nodos secundarios apropiados al árbol 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 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. | |
Table table = new Table(doc); | |
doc.FirstSection.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. | |
Row row = new Row(doc); | |
row.RowFormat.AllowBreakAcrossPages = true; | |
table.AppendChild(row); | |
Cell cell = new Cell(doc); | |
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue; | |
cell.CellFormat.Width = 80; | |
cell.AppendChild(new Paragraph(doc)); | |
cell.FirstParagraph.AppendChild(new Run(doc, "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.LastCell.AppendChild(new Paragraph(doc)); | |
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text")); | |
// We can now apply any auto fit settings. | |
table.AutoFit(AutoFitBehavior.FixedColumnWidths); | |
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx"); |
Crear una tabla desde HTML
Aspose.Words admite la inserción de contenido en un documento desde una fuente HTML utilizando el método InsertHtml. La entrada puede ser una página HTML completa o simplemente un fragmento parcial.
Con el método InsertHtml, los usuarios pueden insertar tablas en el documento mediante etiquetas de tabla como <table>
, <tr>
, <td>
.
El siguiente ejemplo de código muestra cómo insertar una tabla en un documento a partir de una cadena que contiene etiquetas HTML:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Note that AutoFitSettings does not apply to tables inserted from HTML. | |
builder.InsertHtml("<table>" + | |
"<tr>" + | |
"<td>Row 1, Cell 1</td>" + | |
"<td>Row 1, Cell 2</td>" + | |
"</tr>" + | |
"<tr>" + | |
"<td>Row 2, Cell 2</td>" + | |
"<td>Row 2, Cell 2</td>" + | |
"</tr>" + | |
"</table>"); | |
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx"); |
Insertar una copia de una tabla existente
A menudo hay ocasiones en las que es necesario crear una tabla basada en una tabla ya existente en un documento. La forma más sencilla de duplicar una tabla conservando todo el formato es clonar el nodo Tabla utilizando el método Clone.
Se puede utilizar la misma técnica para agregar copias de una fila o celda existente a una tabla.
El siguiente ejemplo de código muestra cómo duplicar una tabla utilizando constructores de nodos:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(MyDir + "Tables.docx"); | |
Table table = (Table) doc.GetChild(NodeType.Table, 0, true); | |
// Clone the table and insert it into the document after the original. | |
Table tableClone = (Table) table.Clone(true); | |
table.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.ParentNode.InsertAfter(new Paragraph(doc), table); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx"); |
El siguiente ejemplo de código muestra cómo clonar la última fila de una tabla y agregarla a la tabla:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(MyDir + "Tables.docx"); | |
Table table = (Table) doc.GetChild(NodeType.Table, 0, true); | |
Row clonedRow = (Row) table.LastRow.Clone(true); | |
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into. | |
foreach (Cell cell in clonedRow.Cells) | |
cell.RemoveAllChildren(); | |
table.AppendChild(clonedRow); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx"); |
Si está pensando en crear tablas en un documento que crezcan dinámicamente con cada registro de su fuente de datos, no se recomienda el método anterior. En cambio, el resultado deseado se logra más fácilmente utilizando Mail merge con regiones. Puedes conocer más sobre esta técnica en la sección “Mail Merge con Regiones”.
Comparar formas de crear una tabla
Aspose.Words proporciona varios métodos para crear nuevas tablas en un documento. Cada método tiene sus propias ventajas y desventajas, por lo que la elección de cuál utilizar depende a menudo de la situación específica.
Echemos un vistazo más de cerca a estas formas de crear tablas y comparemos sus ventajas y desventajas:
Método | Ventajas | Desventajas |
---|---|---|
Vía DocumentBuilder |
El método estándar para insertar tablas y otro contenido de documentos | A veces es difícil crear muchas variedades de tablas al mismo tiempo con la misma instancia del constructor. |
Vía DOM | Se adapta mejor al código circundante que crea e inserta nodos directamente en el DOM sin utilizar un DocumentBuilder | La tabla se crea “vacía”: antes de realizar la mayoría de las operaciones, debe llamar a EnsureMinimum para crear los nodos secundarios que faltan. |
Desde HTML | Puede crear una nueva tabla a partir de una fuente HTML usando etiquetas como <table> , <tr> , <td> |
No todos los formatos posibles de tablas Microsoft Word se pueden aplicar a HTML |
Clonar una tabla existente | Puede crear una copia de una tabla existente conservando todo el formato de filas y celdas. | Los nodos secundarios apropiados deben eliminarse antes de que la tabla esté lista para su uso. |