Como trabalhar com tabelas em .NET
Aspose.Slides FOSS for .NET supports creating tables on slides with configurable column widths and row heights. This guide shows how to add a table, populate it with data, and apply basic text formatting to cells.
Guia passo a passo
Etapa 1: Instale o pacote
dotnet add package Aspose.Slides.FossEtapa 2: Criar ou abrir uma apresentação
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);Etapa 3: Definir larguras de coluna e alturas de linha
Tabelas exigem larguras de coluna e alturas de linha explícitas em pontos (1 ponto = 1/72 polegada). Um slide padrão tem 720 pontos de largura e 540 pontos de altura.
var colWidths = new double[] { 200.0, 150.0, 150.0 }; // 3 columns
var rowHeights = new double[] { 45.0, 40.0, 40.0 }; // 3 rowsEtapa 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);Etapa 5: Definir o texto da célula
Acesse as células via table.Rows[rowIndex][colIndex] e atribua texto através de .TextFrame.Text:
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);Etapa 6: Formatar o texto da célula de cabeçalho
Aplique formatação em negrito às células de cabeçalho usando PortionFormat:
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 Completo Funcional
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 correções
IndexOutOfRangeException ao acessar table.Rows[row][col]
Os índices de linhas e colunas são baseados em zero. Se você definiu rowHeights com 3 elementos, os índices de linha válidos são 0, 1, 2.
O texto da célula não aparece no arquivo salvo
Sempre atribua através de .TextFrame.Text, não através de .Text diretamente no objeto de célula:
// Correct
table.Rows[0][0].TextFrame.Text = "Header";
// Wrong: will not compile or silent failure
// table.Rows[0][0].Text = "Header";A posição da tabela está fora do slide
Verifique se x + sum(colWidths) <= 720 e y + sum(rowHeights) <= 540 para um slide padrão.
Perguntas Frequentes
Posso mesclar células da tabela?
A mesclagem de células não é suportada nesta edição.
Posso aplicar uma cor de fundo em toda a tabela?
Aplique formatação de preenchimento a 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 borda das células?
As propriedades de borda da célula são acessíveis através de cell.CellFormat.BorderLeft, BorderTop, BorderRight, e BorderBottom propriedades. Consulte a referência da API para a lista completa de atributos de formato de borda.