FileFormat.Words es una biblioteca de código abierto que ofrece un módulo de procesador de palabras gratuito que se le permite agregar/modificar las tablas en los documentos de Word.

Cómo hacer una tabla en los archivos de Word usando FileFormat.Words

Descripción general

Una tabla en un documento Word se considera una parte integral cuando se trata de representación de datos. Es el elemento de documento más común y ofrece una gran comodidad en términos de construcción de documentos comerciales. Sorprendentemente, puede crear una tabla en un documento de Word sin usar o instalar MS Word en su máquina local. Sí, permítanme introducir un procesador de palabras gratuito que le permite crear y manipular documentos de Word programáticamente. FileFormat.Words para .NET es un paquete completo de procesamiento de documentos de Word. Por lo tanto, en esta publicación de blog, aprenderemos cómo hacer una tabla en Word documentos usando esta biblioteca .NET FileFormat.Words. Esta publicación de blog cubre las siguientes secciones:

Generador de tabla para Word - Instalación de API

FileFormat.Words para .NET proporciona una amplia gama de características para el procesamiento de palabras de MS. Esta API de código abierto es muy fácil de instalar. Sin embargo, puede descargar su paquete Nuget de instalarlo ejecutando el siguiente comando en el Nuget Package Manager.

Install-Package FileFormat.Words

Cómo crear una tabla en un documento de Word programáticamente

Escribamos algún código para ver este proceso de origen abierto Process de palabras gratis R en acción. De hecho, veremos cómo hacer una tabla en un documento de Word usando FileFormat.Words Biblioteca. Siga los siguientes pasos y el fragmento de código:

  • Inicializar una instancia de la clase documento.
  • Instanciar el constructor de la clase cuerpo con el objeto de clase de documento.
  • Crear un objeto de la clase Tabla.
  • Inicializa los constructores del Toptorder, Bottomboutder, Rightborder, Leftbogar, Insideverticalborder y Inside Horizontalborder clases para Establezca el borde de todos los lados de la mesa.
  • Invoca el método BasicblackSquares_Border para establecer el estilo de borde y el ancho límite.
  • Crear una instancia de la clase TableBorders.
  • Añadir Los objetos del Topoforder, Bottomboder, Rightbower, Leftorder, Inside Virtical Border y Inside HorizontalBorder Classes al objeto de la clase TableBorders.
  • Inicializar una instancia de la clase tableProperties.
  • Invoca el método append de la clase TableProperties para adjuntar el objeto de la clase de TableBorders.
  • Cree una instancia de la clase TableJustificación y llame al método Alignleft para colocar la tabla en el lado izquierdo del documento.
  • Invocar el método append para adjuntar el objeto TableJustificación Table al objeto TBLPROP.
  • El método appendchild de la clase de tabla conectará las propiedades de la tabla a la tabla.
  • Cree un objeto de la clase Tablerow para crear una fila de tabla.
  • Inicializar una instancia de la clase Tablecell.
  • Establezca el encabezado de la primera columna invocando el método TableHeaders.
  • Llame al método append de la clase Tablecell para agregar texto dentro de la celda de la tabla.
  • Crear un objeto de las propiedades de la tabla TableCellProperties
  • Establezca el ancho de la celda de la tabla inicializando el objeto de la clase TableCellWidth y agregue al objeto TblCellProps.
  • El método Append adjuntará el objeto TblCellProps con el objeto de la clase TableCell.
  • Llame al método append para agregar las filas a la tabla.
  • El método AppendChild agregará la tabla al cuerpo del documento.
  • El método Guardar guardará el documento Word en el disco.
using FileFormat.Words;
using FileFormat.Words.Table;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize an instance of the Document class.
            using (Document doc = new Document())
            {
                // Instantiate the constructor of the Body class with the Document class object.
                Body body = new Body(doc);
                // Create an object of the Table class.
                Table table = new Table();
                // Initialize the constructor of the TopBorder class to set the border of the top side of the table.
                TopBorder topBorder = new TopBorder();
                // Invoke the basicBlackSquares_border method to set the border style and border line width.
                topBorder.basicBlackSquares_border(20);
                // To set the border of the bottom side of the table.
                BottomBorder bottomBorder = new BottomBorder();
                bottomBorder.basicBlackSquares_border(20);
                // To set the border of the right side of the table.
                RightBorder rightBorder = new RightBorder();
                rightBorder.basicBlackSquares_border(20);
                // To set the border of the left side of the table.
                LeftBorder leftBorder = new LeftBorder();
                leftBorder.basicBlackSquares_border(20);
                // To set the inside vertical border of the table.
                InsideVerticalBorder insideVerticalBorder = new InsideVerticalBorder();
                insideVerticalBorder.basicBlackSquares_border(20);
                // To set the inside vehorizontalrtical border of the table.
                InsideHorizontalBorder insideHorizontalBorder = new InsideHorizontalBorder();
                insideHorizontalBorder.basicBlackSquares_border(20);
                // Create an instance of the TableBorders class. 
                TableBorders tableBorders = new TableBorders();
                // Append the object of the TopBorder class to the object of the TableBorders class.
                tableBorders.AppendTopBorder(topBorder);
                // Append the object of the BottomBorder class.
                tableBorders.AppendBottomBorder(bottomBorder);
                // Append the object of the RightBorder class.
                tableBorders.AppendRightBorder(rightBorder);
                // Append the object of the LeftBorder class.
                tableBorders.AppendLeftBorder(leftBorder);
                // Append the object of the InsideVerticalBorder class.
                tableBorders.AppendInsideVerticalBorder(insideVerticalBorder);
                // Append the object of the InsideHorizontalBorder class.
                tableBorders.AppendInsideHorizontalBorder(insideHorizontalBorder);

                // Initialize an instance of the TableProperties class.
                TableProperties tblProp = new TableProperties();
                // Invoke the Append method to attach the object of the TableBorders class.
                tblProp.Append(tableBorders);
                // Create an instance of the TableJustification class 
                TableJustification tableJustification = new TableJustification();
                // Call the AlignLeft method to position the table on left side of the document.
                tableJustification.AlignLeft();
                // Invoke the Append method to attach the tableJustification object to the tblProp object.
                tblProp.Append(tableJustification);

                // The AppendChild method will attach the table propertiese to the table.
                table.AppendChild(tblProp);

                // Create an object of the TableRow class to create a table row.
                TableRow tableRow = new TableRow();
                TableRow tableRow2 = new TableRow();

                // Initialize an istance of the TableCell class.
                TableCell tableCell = new TableCell();
                Paragraph para = new Paragraph();
                Run run = new Run();

                // Set the header of the first column by invoking the TableHeaders method.
                table.TableHeaders("Name");
                run.Text = "Mustafa";
                para.AppendChild(run);
                // Call the Append method to add text inside the table cell.
                tableCell.Append(para);

                // Create an object of the TableCellProperties table properties 
                TableCellProperties tblCellProps = new TableCellProperties();

                // Set the width of table cell by initializing the object of the TableCellWidth class and append to tblCellProps object.
                tblCellProps.Append(new TableCellWidth("2400"));
                // Append method will attach the tblCellProps object with the object of the TableCell class.
                tableCell.Append(tblCellProps);

                TableCell tableCell2 = new TableCell();
                Paragraph para2 = new Paragraph();
                Run run2 = new Run();

                // set the header of the second column
                table.TableHeaders("Nationality");
                run2.Text = "Pakistani";
                para2.AppendChild(run2);
                tableCell2.Append(para2);

                TableCellProperties tblCellProps2 = new TableCellProperties();
                tblCellProps2.Append(new TableCellWidth("1400"));
                tableCell2.Append(tblCellProps2);

                TableCell tableCell3 = new TableCell();
                Paragraph para3 = new Paragraph();
                Run run3 = new Run();
                table.TableHeaders("Age");
                run3.Text = "30";
                para3.AppendChild(run3);
                tableCell3.Append(para3);

                TableCellProperties tblCellProps3 = new TableCellProperties();
                tblCellProps3.Append(new TableCellWidth("1400"));
                tableCell3.Append(tblCellProps3);
                // Call the Append method to add cells into table row.
                tableRow.Append(tableCell);
                tableRow.Append(tableCell2);
                tableRow.Append(tableCell3);

                // create table cell
                TableCell _tableCell = new TableCell();
                Paragraph _para = new Paragraph();
                Run _run = new Run();

                _run.Text = "sultan";
                _para.AppendChild(_run);
                _tableCell.Append(_para);

                TableCellProperties tblCellProps1_ = new TableCellProperties();
                tblCellProps1_.Append(new TableCellWidth("2400"));
                _tableCell.Append(tblCellProps1_);


                TableCell _tableCell2 = new TableCell();
                Paragraph _para2 = new Paragraph();
                Run _run2 = new Run();

                _run2.Text = "British";
                _para2.AppendChild(_run2);
                _tableCell2.Append(_para2);

                TableCellProperties tblCellProps2_ = new TableCellProperties();
                tblCellProps2_.Append(new TableCellWidth("1400"));
                _tableCell2.Append(tblCellProps2_);

                TableCell _tableCell3 = new TableCell();
                Paragraph _para3 = new Paragraph();
                Run _run3 = new Run();

                _run3.Text = "2";
                _para3.AppendChild(_run3);
                _tableCell3.Append(_para3);

                TableCellProperties tblCellProps3_ = new TableCellProperties();
                tblCellProps3_.Append(new TableCellWidth("1400"));
                _tableCell3.Append(tblCellProps3_);

                tableRow2.Append(_tableCell);
                tableRow2.Append(_tableCell2);
                tableRow2.Append(_tableCell3);
                // Call the Append method to add the rows into table.
                table.Append(tableRow);
                table.Append(tableRow2);
                // The AppendChild method will add the table to the body of the document.
                body.AppendChild(table);
                // The Save method will save the Word document onto the disk.
                doc.Save("/Docs.docx");
            }

        }

    }
}

La salida del fragmento de código anterior se muestra en la imagen a continuación:

Cómo crear una tabla en un documento de Word

Conclusión

Esto nos lleva al final de este artículo y esperamos que haya aprendido cómo hacer una tabla en un documento de Word usando FileFormat.Words Biblioteca. Además, esta guía lo ayudará si está buscando construir un generador de mesa para documentos de Word en C#. Además, este API gratuito de procesador de textos es de código abierto y puede encontrar su documentación aquí. Finalmente, fileFormat.com continúa escribiendo publicaciones de blog sobre otros temas. Además, puede seguirnos en nuestras plataformas de redes sociales, incluidas Facebook, LinkedIn y Twitter.

Contribuir

Dado que FileFormat.Words para .NET es un proyecto de código abierto y está disponible en GitHub. Entonces, la contribución de la comunidad es muy apreciada.

Haga una pregunta

Puede informarnos sobre sus preguntas o consultas en nuestro Foro.

Preguntas frecuentes-Preguntas frecuentes

** ¿Cómo creo una tabla en un documento de Word?** Es muy fácil crear una tabla en el documento de Word utilizando esta fuente abierta Biblioteca .NET. Además, puede explorar esta API más. ** ¿Cómo crear un archivo DOCX en C#?** Siga este enlace para pasar por un fragmento de código detallado y pasos para crear un archivo DOCX en C#. ** ¿Cómo creo un formato de tabla personalizado en Word?** FileFormat.Words para .NET es una biblioteca gratuita que ofrece características para manipular y crear MS Word programáticamente. De hecho, puede explorar este espacio de nombres fileformat.words.table para ver los métodos y propiedades.

Ver también