C#  PowerPointで文書内の文字を置換


今日はSpire.Presentationという無料のライブラリを使って、パワーポイントで文書内の文字を置換する方法を紹介します。

下準備

1.E-iceblueの公式サイトからFree Spire.Presentation無料版をダウンロードしてください。

2.Visual Studioを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire. Presentation.dllを参照に追加してください。

(Net 4.0を例としたら、デフォルトパスは“Bin→NET4.0→Presentation.dll”というようになります。)

元のファイル

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]);
                    }
                }
            }
        }
    }
}

実行結果