今日はSpire.Presentationという無料のライブラリを使って、パワーポイントで文書内の文字を置換する方法を紹介します。
下準備
1.E-iceblueの公式サイトからFree Spire.Presentation無料版をダウンロードしてください。
2.Visual Studioを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire. Presentation.dllを参照に追加してください。
(Net 4.0を例としたら、デフォルトパスは“Bin→NET4.0→Presentation.dll”というようになります。)
元のファイル
```c# public ReplaceText() { { //Dictionary オブジェクトを作成し、itemを追加します。 Dictionary TagValues = new Dictionary(); TagValues.Add("日本語", "韓国語"); //PowerPointファイルをロードします。 Presentation presentation = new Presentation(); presentation.LoadFromFile("Sample.pptx", FileFormat.Pptx2010); //ReplaceTagsメソッドで文字を置換します。
ReplaceTags(presentation.Slides[0], TagValues);
//保存します。
presentation.SaveToFile("Result.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("Result.pptx");
}
}
public void ReplaceTags(Spire.Presentation.ISlide pSlide, Dictionary TagValues)
{
foreach (IShape curShape in pSlide.Shapes)
{
if (curShape is IAutoShape)
{
foreach (TextParagraph tp in (curShape as IAutoShape).TextFrame.Paragraphs)
{
foreach (var curKey in TagValues.Keys)
{
if (tp.Text.Contains(curKey))
{
tp.Text = tp.Text.Replace(curKey, TagValues[curKey]);
}
}
}
}
}
}
<h4><strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210715/20210715111114.png" alt="f:id:lendoris:20210715111114p:plain" width="554" height="333" loading="lazy" title="" class="hatena-fotolife" itemprop="image" /></p>
<p><strong> </strong></p>