C#/VB.NET: Crie uma tabela no Word

2023-09-27 06:55:05 zaki zou

Instalado via NuGet

PM> Install-Package Spire.Doc

Links Relacionados

No MS Word, as tabelas podem organizar e apresentar os dados em linhas e colunas, o que facilita a compreensão e análise das informações. Neste artigo, você aprenderá como programar crie uma tabela com dados em um documento do Word usando Spire.Doc for .NET.

Instale o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Crie uma tabela simples no Word

Abaixo estão algumas das principais classes e métodos fornecidos pelo Spire.Doc for .NET para criar e formatar tabelas no Word.

Nome Descrição
Classe de mesa Representa uma tabela em um documento do Word.
Classe TableRow Representa uma linha em uma tabela.
Classe TableCell Representa uma célula específica em uma tabela.
Método Section.AddTbale() Adiciona uma nova tabela à seção especificada.
Método Table.ResetCells() Redefine o número da linha e o número da coluna.
Propriedade Table.Rows Obtém as linhas da tabela.
Propriedade TableRow.Height Define a altura da linha especificada.
Propriedade TableRow.Cells Retorna a coleção de células.
Propriedade TableRow.RowFormat Obtém o formato da linha especificada.

As etapas detalhadas são as seguintes

  • Crie um objeto Document e adicione uma seção a ele.
  • Prepare os dados para a linha de cabeçalho e outras linhas, armazenando-os em uma matriz de strings unidimensional e em uma matriz de strings bidimensional, respectivamente.
  • Adicione uma tabela à seção usando o método Section.AddTable().
  • Insira dados na linha do cabeçalho e defina a formatação da linha, incluindo altura da linha, cor de fundo e alinhamento do texto.
  • Insira dados no restante das linhas e aplique formatação a essas linhas.
  • Salve o documento em outro arquivo usando o método Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using System.Drawing;
    using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    
    namespace WordTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
                //Add a section
                Section s = doc.AddSection();
    
                //Define the data for the table
                String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" };
                String[][] data = {
                                      new String[]{ "08/07/2021","Dive kayak","United States","24","16"},
                                      new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"},
                                      new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"},
                                      new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"},
                                      new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"},
                                      new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"},
                                      new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"},
                                      new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"},
                                  };
                //Add a table
                Table table = s.AddTable(true);
                table.ResetCells(data.Length + 1, Header.Length);
    
                //Set the first row as table header
                TableRow FRow = table.Rows[0];
                FRow.IsHeader = true;
    
                //Set the height and color of the first row
                FRow.Height = 23;
                FRow.RowFormat.BackColor = Color.LightSeaGreen;
                for (int i = 0; i < Header.Length; i++)
                {
                    //Set alignment for cells
                    Paragraph p = FRow.Cells[i].AddParagraph();
                    FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    p.Format.HorizontalAlignment = HorizontalAlignment.Center;
    
                    //Set data format
                    TextRange TR = p.AppendText(Header[i]);
                    TR.CharacterFormat.FontName = "Calibri";
                    TR.CharacterFormat.FontSize = 12;
                    TR.CharacterFormat.Bold = true;
                }
    
                //Add data to the rest of rows and set cell format
                for (int r = 0; r < data.Length; r++)
                {
                    TableRow DataRow = table.Rows[r + 1];
                    DataRow.Height = 20;
                    for (int c = 0; c < data[r].Length; c++)
                    {
                        DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        Paragraph p2 = DataRow.Cells[c].AddParagraph();
                        TextRange TR2 = p2.AppendText(data[r][c]);
                        p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
    
                        //Set data format
                        TR2.CharacterFormat.FontName = "Calibri";
                        TR2.CharacterFormat.FontSize = 11;
                    }
                }
    
                //Save the document
                doc.SaveToFile("WordTable.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Create a Table in Word

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também