如果今天有一份很制式的報告需撰寫,我們可以從資料庫將相關資料填寫至事先建立的標準範本,這樣固定格式資料就能自動幫忙填寫。 

本文API採用NetOffice 下載路徑

 

1. 加入4個參考檔

 

NetOffice.dll OfficeApi.dll PowerPointApi.dll VBIDEApi.dll

image

 

 

2.將4個參考檔的屬性 "內嵌Interop" 設為false

 

image

 

[3. 程式碼]

 

using PowerPoint = NetOffice.PowerPointApi;
using NetOffice.OfficeApi.Enums;
using NetOffice.PowerPointApi;


using (PowerPoint.Application app = new PowerPoint.Application())
            {
                string newFilePath = @"D:\smart.pptx";  //PowerPoint範本路徑
                Presentation presentation = app.Presentations.Open(newFilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); //開啟檔案
                int lastSlideIndex = presentation.Slides.Count; //PowerPoint內投影片數量
                Slide slide = presentation.Slides[1]; //取得第一個投影片
                int shapesCount = slide.Shapes.Count; //投影片內的快取圖案數量

                for (int i = 1; i <= shapesCount; i++) {
                    TextRange objTextRng = slide.Shapes[i].TextFrame.TextRange; //取得每一個快取圖案為文字框類型
                    string objText = objTextRng.Text; //取得快取圖案的內容
                    switch  (objText)
                    {
                        case "[NAME]": //取代文字
                            objTextRng.Text = "風景圖";
                            break;
                        case "[IMG1]": //插入圖片
                            string picturePath = @"D:\001.png"; //圖案位置
                            Shape shape = slide.Shapes[i]; //取得快取圖案
                            slide.Shapes.AddPicture(picturePath,MsoTriState.msoFalse, MsoTriState.msoTrue, shape.Left, shape.Top,300);//插入圖片
                            slide.Shapes[i].Delete();//刪除原位置的快取圖案
                            break;
                    }
                }     

                string filename = string.Format(@"d:\samrt.pptx");
                presentation.SaveAs(filename);

                app.Quit();
                app.Dispose();

 

image

PowerPoint範本

 

image

修改後的PowerPoint檔案

 

[其他說明]

 

建立線條

slide.Shapes.AddLine(x1,y1,x2,y2) 

 

建立文字框

PowerPoint.Shape label =  slide.Shapes.AddLabel(MsoTextOrientation.msoTextOrientationHorizontal, left, top, width, height); //設定位置left top與大小width height
label.TextFrame.TextRange.Text = "文字內容";

arrow
arrow
    全站熱搜

    門外漢 發表在 痞客邦 留言(0) 人氣()