Como trabalhar com tabelas no .NET

Como trabalhar com tabelas no .NET

Este guia mostra como criar tabelas em slides do PowerPoint usando Aspose.Slides FOSS para .NET. Call slide.Shapes.AddTable(x, y, columnWidths, rowHeights) para adicionar uma tabela, acessar células via table.Rows[row][col], e aplicar a formatação de texto através do PortionFormat em cada célula.

Guia passo a passo

Passo 1: Instalar o pacote

Adicione a seguinte referência de pacote ao seu projeto executando o comando dotnet CLI install:

aspose-slides-foss/slides is not yet published — build from source until it ships. See the project README for build instructions.


Passo 2: Crie ou abra uma apresentação

Utilize um using declaração para construir um Presentation, acessar o primeiro slide via prs.Slides[0], depois salva quando terminado:

using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;

using var prs = new Presentation();
var slide = prs.Slides[0];
// ... add table ...
prs.Save("table.pptx", SaveFormat.Pptx);

Passo 3: Defina largura de coluna e altura das linhas

As tabelas exigem largura explícita de colunas e alturas de linhas em pontos (1 ponto = 1/72 polegada). Um slide padrão tem 720 pontos de largurade e 540 pontosde altura.

var colWidths = new double[] { 200.0, 150.0, 150.0 };   // 3 columns
var rowHeights = new double[] { 45.0, 40.0, 40.0 };     // 3 rows

Passo 4: Adicionar a tabela

slide.Shapes.AddTable(x, y, columnWidths, rowHeights) Cria a tabela na posição (x, y):

using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;

using var prs = new Presentation();
var slide = prs.Slides[0];

var colWidths = new double[] { 200.0, 150.0, 150.0 };
var rowHeights = new double[] { 45.0, 40.0, 40.0 };
var table = slide.Shapes.AddTable(50, 100, colWidths, rowHeights);

prs.Save("table.pptx", SaveFormat.Pptx);

Passo 5: Configurar texto de célula

Células de acesso via table.Rows[rowIndex][colIndex] e atribuir texto através de: .TextFrame.Text.Os índices de linha e coluna são baseados em zero, portanto a linha do cabeçalho é o índice 0 e as linhas de dados começam no índize 1:

using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;

using var prs = new Presentation();
var slide = prs.Slides[0];

var colWidths = new double[] { 200.0, 150.0, 150.0 };
var rowHeights = new double[] { 45.0, 40.0, 40.0 };
var table = slide.Shapes.AddTable(50, 100, colWidths, rowHeights);

// Header row (row 0)
string[] headers = { "Product", "Units Sold", "Revenue" };
for (int col = 0; col < headers.Length; col++)
    table.Rows[0][col].TextFrame.Text = headers[col];

// Data rows
string[][] data = {
    new[] { "Widget A", "1,200", "$24,000" },
    new[] { "Widget B", "850", "$17,000" },
};
for (int rowIdx = 0; rowIdx < data.Length; rowIdx++)
    for (int col = 0; col < data[rowIdx].Length; col++)
        table.Rows[rowIdx + 1][col].TextFrame.Text = data[rowIdx][col];

prs.Save("sales-table.pptx", SaveFormat.Pptx);

Passo 6: Formatear texto da célula de cabeçalho

Aplicar o formato de fonte em negrito para células do cabeçalho acessando a primeira seção da página. PortionFormat via: cell.TextFrame.Paragraphs[0].Portions[0].PortionFormat e de fixação fmt.FontBold = NullableBool.True:

using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Drawing;

for (int col = 0; col < headers.Length; col++)
{
    var cell = table.Rows[0][col];
    var portions = cell.TextFrame.Paragraphs[0].Portions;
    if (portions.Count > 0)
    {
        var fmt = portions[0].PortionFormat;
        fmt.FontBold = NullableBool.True;
        fmt.FillFormat.FillType = FillType.Solid;
        fmt.FillFormat.SolidFillColor.Color = Color.FromArgb(255, 255, 255, 255);
    }
}

Exemplo de trabalho completo

O seguinte script autônomo cria uma tabela de receita regional com uma linha de cabeçalho em negrito e quatro linhas de dados, depois salva o resultado como um arquivo PPTX:

using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Drawing;
using Aspose.Slides.Foss.Export;

string[][] dataRows = {
    new[] { "North", "$1.2M", "+8%" },
    new[] { "South", "$0.9M", "+4%" },
    new[] { "East",  "$1.5M", "+12%" },
    new[] { "West",  "$0.7M", "+2%" },
};
string[] headers = { "Region", "Revenue", "Growth" };

using var prs = new Presentation();
var slide = prs.Slides[0];

var colWidths = new double[] { 180.0, 140.0, 120.0 };
var rowHeights = new double[dataRows.Length + 1];
rowHeights[0] = 45.0;
for (int i = 1; i < rowHeights.Length; i++) rowHeights[i] = 38.0;

var table = slide.Shapes.AddTable(60, 80, colWidths, rowHeights);

// Header row
for (int col = 0; col < headers.Length; col++)
{
    var cell = table.Rows[0][col];
    cell.TextFrame.Text = headers[col];
    if (cell.TextFrame.Paragraphs[0].Portions.Count > 0)
    {
        var fmt = cell.TextFrame.Paragraphs[0].Portions[0].PortionFormat;
        fmt.FontBold = NullableBool.True;
    }
}

// Data rows
for (int rowIdx = 0; rowIdx < dataRows.Length; rowIdx++)
    for (int col = 0; col < dataRows[rowIdx].Length; col++)
        table.Rows[rowIdx + 1][col].TextFrame.Text = dataRows[rowIdx][col];

prs.Save("regional-revenue.pptx", SaveFormat.Pptx);
Console.WriteLine("Saved regional-revenue.pptx");

Problemas comuns e soluções

IndexOutOfRangeException quando acederem table.Rows[row][col]

Os índices de linha e coluna são baseados em zero. Se você definir rowHeights com 3 elementos, os índices de linha válidos são 0, 1, 2.

Não há texto na célula no arquivo de armazenamento .

Sempre atribuir através de .TextFrame.Text, não através de .Text diretamente no objeto da célula. .Text em uma célula de tabela não compila ou falha silenciosamente.

A posição da mesa está fora do slide.

Verifica isso . x + sum(colWidths) <= 720 e a) y + sum(rowHeights) <= 540 para um slide padrão.


Perguntas Frequentes

Posso juntar células de mesa?

Sim, usa. Table.MergeCells(ICell cell1, ICell cell2, bool allowSplitting) para fundir duas células adjacentes. Set allowSplitting a) para o false Para evitar que a célula fusionada seja dividida novamente. Exemplo:

// Merge cell (row 0, col 0) with cell (row 0, col 1)
var cell1 = table.Rows[0][0];
var cell2 = table.Rows[0][1];
table.MergeCells(cell1, cell2, false);

Posso aplicar uma cor de fundo para toda a mesa?

Aplicar a formatação de preenchimento para cada célula individual:

using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Drawing;

for (int row = 0; row < table.Rows.Count; row++)
    for (int col = 0; col < table.Rows[row].Count; col++)
    {
        var cell = table.Rows[row][col];
        cell.CellFormat.FillFormat.FillType = FillType.Solid;
        cell.CellFormat.FillFormat.SolidFillColor.Color = Color.FromArgb(255, 240, 248, 255);
    }

Posso definir estilos de fronteira da célula?

As propriedades de fronteira celular são acessíveis através do cell.CellFormat.BorderLeft, BorderTop, BorderRight, e BorderBottom Propriedades: Consulte a referência da API para obter uma lista completa dos atributos do formato de bordas.


Ver também:

 Português