FileFormat.words é uma biblioteca de código aberto que oferece um módulo de processador de texto gratuito que permite programaticamente adicionar/modificar tabelas nos documentos do Word.

Como fazer uma tabela em arquivos do Word usando o FileFormat.words

Visão geral {.wp-block-heading} Uma tabela em um documento Word é considerada uma parte integrante quando se trata de representação de dados. É o elemento de documento mais comum e oferece grande conveniência em termos de construção de documentos de negócios. Surpreendentemente, você pode criar uma tabela em um documento do Word sem usar ou instalar MS Word em sua máquina local. Sim, deixe -me apresentar um Processador de texto gratuito que permite criar e manipular documentos de palavras programaticamente. FileFormat.words para .net é um pacote completo de processamento de documentos do Word. Portanto, nesta postagem do blog, aprenderemos como fazer uma tabela no word documentos usando esta biblioteca .NET FileFormat.words. Esta postagem do blog aborda as seguintes seções:

Gerador de tabela para Word - Instalação da API

FileFormat.words para .net fornece uma ampla gama de recursos para o processamento de texto do MS. Esta API de código aberto é muito fácil de instalar. No entanto, você pode fazer o download do seu Nuget Package de instalá -lo executando o seguinte comando no Nuget Package Manager.

Install-Package FileFormat.Words

Como criar uma tabela em um documento do Word programaticamente

Vamos escrever algum código para ver esse processo aberto Processo de texto gratuito r em ação. De fato, veremos como fazer uma tabela em um documento do Word usando a biblioteca FileFormat.words. Siga as etapas a seguir e o trenó de código:

  • Inicialize uma instância da classe Document.
  • Instanciar o construtor da classe 10 com o objeto da classe de documentos.
  • Crie um objeto da classe tabela.
  • Inicialize os construtores do Topborder, Bottomborder, Rightborder, esquerda, Inside -Terticalborder e Inside Horizontalborder classes para Defina a borda de todos os lados da mesa.
  • Invoque o método Basicblacksquares_border para definir o estilo de fronteira e a largura limítrofe.
  • Crie uma instância da classe Tableborders.
  • Appender Os objetos do Topborder, Bottomborder, RightDorder, esquerda, Inside Terticalborder e Inside Horizontalborder Classes para o objeto da classe Tableborders.
  • Inicialize uma instância da classe TableProperties.
  • Invoque o método Apêndos da classe TableProperties para anexar o objeto da classe Tableborders.
  • Crie uma instância da classe Tablejustification e chame o método alignleft para posicionar a tabela no lado esquerdo do documento.
  • Invocar o método APÊNDAR para anexar o objeto de ajuste de tabela ao objeto TBLProp.
  • O método AppendChild da classe de tabela anexará as propriedades da tabela à tabela.
  • Crie um objeto da classe Tablerow para criar uma linha de tabela.
  • Inicialize uma instância da classe tablecl.
  • Defina o cabeçalho da primeira coluna, invocando o método TableHeaders.
  • Ligue para o método Apêndos da classe TableCell para adicionar texto dentro da célula da tabela.
  • Crie um objeto das TableCellproperties Tabela Properties
  • Defina a largura da célula da tabela, inicializando o objeto da classe TableCellWidth e anexa ao objeto TBLCellProps.
  • O método Apêndos anexará o objeto TBLCELLPROPS ao objeto da classe TableCell.
  • Ligue para o método Apêndos para adicionar as linhas à tabela.
  • O método AppendChild adicionará a tabela ao corpo do documento.
  • O método Salvar salvará o documento do Word no 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");
            }

        }

    }
}

A saída do snippet de código acima é mostrada na imagem abaixo:

Como criar uma tabela em um documento do Word

Conclusão

Isso nos leva ao final deste artigo e esperamos que você tenha aprendido como fazer uma tabela em um documento Word usando a biblioteca FileFormat.words. Além disso, este guia o ajudará se você deseja criar um gerador de tabela para documentos do Word em C#. Além disso, esta API de texto livre é de código aberto e você pode encontrar sua documentação aqui. Finalmente, FileFormat.com continua a escrever postagens no blog sobre outros tópicos. Além disso, você pode nos seguir em nossas plataformas de mídia social, incluindo Facebook, LinkedIn e Twitter.

Contribua

Desde FileFormat.words para .net é um projeto de código aberto e está disponível no Github. Portanto, a contribuição da comunidade é muito apreciada.

Faça uma pergunta

Você pode nos informar sobre suas perguntas ou consultas em nosso fórum.

Perguntas frequentes-perguntas frequentes

** Como faço para criar uma tabela em um documento do Word?** É muito fácil criar uma tabela no documento do Word usando esta fonte aberta .NET Library. Além disso, você pode explorar esta API mais. ** Como criar um arquivo DOCX em C#?** Siga este link para passar por um trecho de código detalhado e etapas para criar um arquivo DOCX em C#. ** Como faço para criar um formato de tabela personalizado no Word?** FileFormat.Words for .Net é uma biblioteca gratuita que oferece recursos para manipular e criar o MS Word programaticamente. De fato, você pode explorar este espaço para nome FileFormat.words.Table para ver os métodos e propriedades.

veja também