using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using POWERPOINT = Microsoft.Office.Interop.PowerPoint;
using OFFICECORE = Microsoft.Office.Core;
using Microsoft.SqlServer.Server;
using Microsoft.Office.Core;
namespace ConsoleApp1
{
class Program
{
public static POWERPOINT.Application objApp =null;
public static POWERPOINT.Presentation objPresSet = null;
POWERPOINT.SlideShowWindows objSSWs;
POWERPOINT.SlideShowTransition objSST;
POWERPOINT.SlideShowSettings objSSS;
POWERPOINT.SlideRange objSldRng;
static void Main(string[] args)
{
var uuid = Guid.NewGuid().ToString();
FileRemove(uuid);
}
/// <summary>
/// 创建模板文件
/// </summary>
/// <param name="id">GUID--讲评的ID</param>
public static void FileRemove(string id)
{
//根据GUID生成文件夹
Directory.CreateDirectory(@"../Upload/" + id);
//找到原始文件
String sourcePath = "../Upload/Dome.ppt";
String targetPath = "../Upload/"+id+"/"+id+".ppt";
bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
File.Copy(sourcePath, targetPath, isrewrite);
Program program = new Program();
program.PPTOpen(targetPath);
//循环编写Code以达到批量替换
program.ReplaceAll("系统录入编写人", "GK");
program.PPTpic();
program.PPTClose();
}
/// <summary>
/// 打开PPT
/// </summary>
/// <param name="filePath"></param>
public void PPTOpen(string filePath)
{
//防止连续打开多个PPT程序.
if (objApp != null) { return; }
try
{
objApp = new POWERPOINT.Application();
//objApp.ShowInTaskBar
//objApp.DisplayGuides = MsoTriState.msoFalse;
FileInfo fileInfo = new FileInfo(@""+filePath+"");
objPresSet = objApp.Presentations.Open(fileInfo.FullName, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse);
objApp.Assistant.On = false;
objSSS = objPresSet.SlideShowSettings;
objSSS.Run();
}
catch (Exception ex)
{
objApp.Quit();
}
}
public void ReplaceAll(string OldText, string NewText)
{
//页面总页数
int num = objApp.Presentations.Count;
for (int j = 1; j <= num; j++)
{
//循环PPT页
POWERPOINT.Slide slide = objPresSet.Slides[j];
for (int i = 1; i <= slide.Shapes.Count; i++)
{
POWERPOINT.Shape shape = slide.Shapes[i];
if (shape.TextFrame != null)
{
POWERPOINT.TextFrame textFrame = shape.TextFrame;
try
{
if (textFrame.TextRange != null)
{
//替换文字操作方法
textFrame.TextRange.Replace(OldText, NewText);
}
}
catch
{ }
}
}
}
}
/// <summary>
///
/// </summary>
public void PPTpic()
{
POWERPOINT.CustomLayout slides = objPresSet.Slides[1].CustomLayout;
objPresSet.Slides.AddSlide(5,slides);
POWERPOINT.Slide slide = objPresSet.Slides[5];
slide.Shapes.AddPicture("C:/Users/l/Desktop/ConsoleApp1/ConsoleApp1/Upload/8b5491cd-1e75-42f9-90e8-8de7780f3219.png",MsoTriState.msoFalse,MsoTriState.msoTrue, 1, 1, 700, 500);
}
// <summary>
/// 关闭PPT文档。
/// </summary>
public void PPTClose()
{
//装备PPT程序。
if (objPresSet != null)
{
objPresSet.Save();
}
if (objApp != null)
objApp.Quit();
GC.Collect();
}
}
}