如何使用 C# 在 PowerPoint 中创建表格

本文指导如何使用 C# 在 PowerPoint 中创建表格。它提供了建立环境的所有详细信息、创建和填充表格的分步过程,以及演示如何使用 C# 在幻灯片中插入表格的可运行示例代码。您还将学习格式化表格中的文本,并将生成的演示文稿以 PPTPPTX 或 MS PowerPoint 支持的任何其他格式保存在磁盘上。

使用 C# 在 PowerPoint 中创建表格的步骤

  1. 建立环境添加 Aspose.Slides for .NET 添加表
  2. 使用 Presentation 类创建一个新的演示文稿并访问其第一张幻灯片
  3. 使用 AddTable() 方法在幻灯片中添加具有定义的行和列高度的表格
  4. 遍历新添加表格的每一行和单元格
  5. 在每个单元格中设置一些文本并设置其字体
  6. 将演示文稿保存为 PPT 格式

这些步骤解释了如何使用 C# 在 PowerPoint 中制作表格。首先,您可以创建一个演示文稿并访问其中默认包含一组形状的第一张幻灯片。在接下来的步骤中,通过提供单元格中文本左上角位置的 X 和 Y 坐标以及描述行高和列宽的整数数组来创建表格。在最后的步骤中,创建一个 ITextFrame 类对象并在保存输出文件之前根据您的要求设置文本段落格式。

使用 C# 在 PowerPoint 中添加表格的代码

using Aspose.Slides;
using Aspose.Slides.Export;
namespace AsposeProjects
{
class Program
{
static void Main(string[] args) // Main function to add table in a slide using C#
{
// Initialize license
License lic = new License();
lic.SetLicense("Aspose.Total.lic");
// Instantiate a new presentation
Presentation presentation = new Presentation();
// Access the first slide from the default collection
ISlide sld = presentation.Slides[0];
// Specify the rows heights and columns widths
double[] columnsWidths = { 45, 45, 45 };
double[] rowsHeights = { 45, 26, 26, 26, 26 };
// Insert a new table
Aspose.Slides.ITable table = sld.Shapes.AddTable(55, 55, columnsWidths, rowsHeights);
// Fill the table and set the font
foreach (IRow row in table.Rows)
{
foreach (ICell cell in row)
{
// Access the cell's text frame
ITextFrame textFormat = cell.TextFrame;
// Set text in the cell
textFormat.Text = "Data " + cell.FirstRowIndex.ToString() + cell.FirstColumnIndex.ToString();
// Set text font
textFormat.Paragraphs[0].Portions[0].PortionFormat.FontHeight = 10;
textFormat.Paragraphs[0].ParagraphFormat.Bullet.Type = BulletType.None;
}
}
// Save the presentation on the disk
presentation.Save("PresentationTable.ppt", SaveFormat.Ppt);
System.Console.WriteLine("Done");
}
}
}
此代码有助于如何使用 C# 在 PowerPoint 中创建表,其中 Aspose.Slides.ITable 对象用于创建一个表,该表默认具有行和列的集合,用于将数据插入其中。 ITextFrame 类对象设置文本、字体高度和项目符号类型。您可以设置其他属性,例如突出显示文本、添加或删除字段、设置填充格式以及设置突出显示颜色等等。

本教程描述了如何使用 C# 在演示文稿中插入表格。如果您想了解保护 PowerPoint 演示文稿的过程,请参阅 如何在 C# 中保护 PowerPoint 演示文稿 上的文章。

 简体中文