Open5

.NET6環境下で既存のOfficeファイルを読み込み制御してみる(#雑メモ)

Kohei OgawaKohei Ogawa

.NET6環境でC#のコンソールアプリ用のテンプレ選択したら、見慣れたこのコードじゃなくてまず驚いた

using System;

namespace MyApp // Note: actual namespace depends on the project name.
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

こう出力されて、「プログラムに記述する必要があるコードを簡素化できる最新の C# 機能が使用されています」とのこと。

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

https://docs.microsoft.com/ja-jp/dotnet/core/tutorials/top-level-templates

Kohei OgawaKohei Ogawa

1枚目のスライドに画像掲載されているpptxファイルを対象に、置換する画像ファイルのパスを指定して、プログラムから制御することができた。

▼変換前

▼変換後

using ShapeCrawler;
namespace Pictures;

internal class PictureSamples
{
    internal void Picture()
    {
        using IPresentation presentation = SCPresentation.Open(@"<対象pptxファイル>", isEditable: true);

        // Get picture shape
        IPicture picture = presentation.Slides[0].Shapes.OfType<IPicture>().First(); // 1スライド目に含まれる画像を対象

        // Change imag
        picture.Image.SetImage(@"<置換後の画像ファイルパス>");

        // Save changes
        presentation.Save();
    }
}
Kohei OgawaKohei Ogawa

これで、SharePoint上のOfficeファイルやAzureサービスとの連携周りが実装できそうなので、大変嬉しい(ここには気が向いたら書くかも)