C# 實現對PPT插入、編輯、刪除表格


現代學習和辦公當中,經常會接觸到對表格的運用,像各種單據、報表、賬戶等等。在PPT演示文稿中同樣不可避免的應用到各種數據表格。對於在PPT中插入表格,我發現了一個新方法,不過我用到了一款免費的.NET組件——Free Spire.Presentation,在C#中添加該產品DLL文件,可以簡單快速地實現對演示文稿的表格插入、編輯和刪除等操作。有需要的話可以在下面的網址下載:https://www.e-iceblue.cn/Downloads/Free-Spire-Presentation-NET.html

1.插入表格

步驟一:創建一個PowerPoint文檔

Presentation ppt = new Presentation();
ppt.SlideSize.Type = SlideSizeType.Screen16x9;

步驟二:初始化一個ITable實例,並指定位置、行數和列數、行高和列寬

double[] widths = new double[] { 100, 100, 100, 100, 100 };
double[] heights = new double[] { 15, 15, 15, 15, 15 };
ITable table = ppt.Slides[0].Shapes.AppendTable(80, 80, widths, heights);

步驟三:為表格設置內置格式

table.StylePreset = TableStylePreset.LightStyle1Accent2;

步驟四:聲明並初始化一個String[,]數組

string[,] data = new string[,]
{
    {"排名","姓名","銷售額","回款額","工號"},
    {"1","李彪","18270","18270","0011"},
    {"2","李娜","18105","18105","0025"},
    {"3","張麗","17987","17987","0008"},
    {"4","黃艷","17790","17790","0017"},
};

步驟六:保存文檔

ppt.SaveToFile("創建表格.pptx", FileFormat.Pptx2010);

完成操作后得到以下PPT文檔效果

2.刪除表格行與列

步驟一:初始化一個Presentation實例並加載一個PowerPoint文檔

Presentation ppt = new Presentation();
ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\創建表格.pptx");

步驟二:獲取第一張幻燈片上的表格

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        table[j, i].TextFrame.Text = data[i, j];
        table[j, i].TextFrame.Paragraphs[0].TextRanges[0].LatinFont = new TextFont("Arial");
    }
}

步驟三:刪除第四列及第四行

table.ColumnsList.RemoveAt(3, false);
table.TableRows.RemoveAt(4, false);

步驟四:保存文檔

ppt.SaveToFile("刪除行與列.pptx", FileFormat.Pptx2010);

3.刪除表格

步驟一:初始化一個Presentation實例並加載一個PowerPoint文檔

Presentation ppt = new Presentation();
ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\創建表格.pptx");

步驟二:初始化一個List對象,元素類型為IShape

List<IShape> tableShapes = new List<IShape>();

步驟三:獲取第一張幻燈片上所有的表格圖形並添加到List

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        table[j, i].TextFrame.Text = data[i, j];
        table[j, i].TextFrame.Paragraphs[0].TextRanges[0].LatinFont = new TextFont("Arial");
    }
}

步驟四:從幻燈片刪除第一個表格圖形

ppt.Slides[0].Shapes.Remove(tableShapes[0]);

步驟五:保存文檔

ppt.SaveToFile("刪除表格.pptx", FileFormat.Pptx2010);

 

以上是本人使用Free Spire.Presentation這款組件對PPT文檔中表格的一些操作,希望能提供幫助,感謝閱讀!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM