前一段时间因工作需要,需增加ppt数据的导出下载。发现网络上这方面资料并不是很多,零零散散地找到一些相关的资料,经过自己的试验,终于完成相关功能。应博友要求,在此分享下我的经验,不好之处还望大家多多指出。
在做之前,首先需要添加相关引用Microsoft.Office.Interop.PowerPoint.dll。
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
操作PPT代码如下:
复制代码
public void createPPT() { try { //ppt存储路径 string path = string.Format("{0}/{1}.ppt", Server.MapPath("."), DateTime.Now.Ticks.ToString()); //ppt引用的模版路径 string MyTemplateFile = "d:\\test.pot"; PowerPoint.ApplicationClass MyApp; PowerPoint.Presentations MyPresSet; PowerPoint._Presentation MyPres; PowerPoint.Shape objShape; PowerPoint.Slides objSlides; PowerPoint._Slide MySlide; PowerPoint.TextRange objTextRng; PowerPoint.Table table = null; MyApp = new PowerPoint.ApplicationClass(); //如果已存在,则删除 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; //套用模版 MyPres = MyApp.Presentations.Open(MyTemplateFile, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); MyPresSet = MyApp.Presentations; objSlides = MyPres.Slides; //创建第一张PPT ppLayoutTitle指定模板首页 MySlide = objSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitle); //添加一行文字(left:10,top:110,width:700,height:400) objTextRng = MySlide.Shapes.AddLabel(MsoTextOrientation.msoTextOrientationHorizontal, 10, 110, 700, 400).TextFrame.TextRange; objTextRng.Text = " PPT"; objTextRng.Font.Color.RGB = 0x66CCFF; //设置字的颜色 objTextRng.Font.Size = 42; //字号 //创建第二张PPT ppLayoutBlank指定无标题页 MySlide = objSlides.Add(2, PowerPoint.PpSlideLayout.ppLayoutBlank); //插入图片 MySlide.Shapes.AddPicture("1.jpg", MsoTriState.msoFalse, MsoTriState.msoTrue, 110, 140, 500, 300); //创建第三张PPT ppLayoutTitleOnly指定仅有标题页 MySlide = objSlides.Add(3, PowerPoint.PpSlideLayout.ppLayoutTitleOnly); objTextRng = MySlide.Shapes[1].TextFrame.TextRange; objTextRng.Text = "目录"; objTextRng.Font.Size = 32; //插入图片 MySlide.Shapes.AddPicture("1.jpg", MsoTriState.msoFalse, MsoTriState.msoTrue, 110, 140, 500, 300); //创建第四张PPT MySlide = objSlides.Add(3, PowerPoint.PpSlideLayout.ppLayoutBlank); //添加一个表格 objShape = MySlide.Shapes.AddTable(3, 3, 105, 150, 400, 100); table = objShape.Table; for (int i = 1; i <= table.Rows.Count; i++) { for (int j = 1; j <= table.Columns.Count; j++) { table.Cell(i, j).Shape.TextFrame.TextRange.Font.Size = 12; table.Cell(i, j).Shape.TextFrame.TextRange.Text = string.Format("[{0},{1}]", i, j); } } //保存格式 PowerPoint.PpSaveAsFileType format = PowerPoint.PpSaveAsFileType.ppSaveAsDefault; //内容保存 MyPres.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse); //关闭excelDoc文档对象 MyPres.Close(); //关闭excelApp组件对象 MyApp.Quit(); }
您可能感兴趣的文章: