Sök och ersätt text utan att förlora format i presentation

Båda metoderna följer dessa steg:

  • Öppna en presentation.
  • Sök efter texten.
  • Ersätt texten.
  • Skriv presentationen.

VSTO


 private void findReplaceText(string strToFind, string strToReplaceWith)

{

//Öppna presentationen

PowerPoint.Presentation pres = null;

pres = Globals.ThisAddIn.Application.Presentations.Open("mytextone.ppt",

						  Microsoft.Office.Core.MsoTriState.msoFalse,

						  Microsoft.Office.Core.MsoTriState.msoFalse,

						  Microsoft.Office.Core.MsoTriState.msoFalse);

//Loopa igenom bildspel

foreach (PowerPoint.Slide sld in pres.Slides)

	//Loopa igenom alla former i bilden

	foreach (PowerPoint.Shape shp in sld.Shapes)

	{

		//Hämta texten i formen

		string str = shp.TextFrame.TextRange.Text;

		//Hitta text att ersätta

		if (str.Contains(strToFind))

		//Ersätt befintlig text med den nya texten

		{

			int idx = str.IndexOf(strToFind);

			string strStartText = str.Substring(0, idx);

			string strEndText = str.Substring(idx + strToFind.Length, str.Length - 1 - (idx + strToFind.Length - 1));

			shp.TextFrame.TextRange.Text = strStartText + strToReplaceWith + strEndText;

		}

		pres.SaveAs("MyTextOne___.ppt",

		PowerPoint.PpSaveAsFileType.ppSaveAsPresentation,

		Microsoft.Office.Core.MsoTriState.msoFalse);

	}

Aspose.Slides


 private static void findReplaceText(string strToFind, string strToReplaceWith)

{

	//Öppna presentationen

	Presentation pres = new Presentation("mytextone.ppt");

	//Hämta alla textrutor i presentationen

	ITextBox[] tb = PresentationScanner.GetAllTextBoxes(pres, false);

	for (int i = 0; i < tb.Length; i++)

		foreach (Paragraph para in tb[i].Paragraphs)

			foreach (Portion port in para.Portions)

				//Hitta text som ska ersättas

				if (port.Text.Contains(strToFind))

				//Ersätt befintlig text med den nya texten

				{

					string str = port.Text;

					int idx = str.IndexOf(strToFind);

					string strStartText = str.Substring(0, idx);

					string strEndText = str.Substring(idx + strToFind.Length, str.Length - 1 - (idx + strToFind.Length - 1));

					port.Text = strStartText + strToReplaceWith + strEndText;

				}

	pres.Write("myTextOneAspose.ppt");

}

Ladda ner exempelkod