C# GraphAPIでOneDriveにExcelを新規作成するサンプルプログラム

# アクセストークン取得:方法1

            string accessToken ="";
            //API URL
            var url = "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token";

            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Method = "POST";

            httpRequest.ContentType = "application/x-www-form-urlencoded";

            var data = "grant_type=client_credentials&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_id=535fb089-9ff3-47b6-9bfb-4f1264799865&client_secret=qWgdYAmab0YSkuL1qKv5bPX";

            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(data);
            }

            
            var httpResponse = (HttpWebResponse)httpRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                dynamic dataArr = JOBject.Parse(result);
                accessToken = dataArr.access_token;
            }

            Console.WriteLine(httpResponse.StatusCode);
# アクセストークン取得：方法②
```
using Microsoft.Graph;

var scopes = new string[] { "https://graph.microsoft.com/.default" };

// Configure the MSAL client as a confidential client
var confidentialClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithAuthority($"https://login.microsoftonline.com/$tenantId/v2.0")
    .WithClientSecret(clientSecret)
    .Build();

// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient
                .AcquireTokenForClient(scopes)
                .ExecuteAsync();

//認証
var authProvider = new DelegateAuthenticationProvider(request =>
{
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                    return Task.CompletedTask;
                });
```

# 認証
                //認証
                var authProvider = new DelegateAuthenticationProvider(request =>
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "ここにアクセストークンを入力してください");
                    return Task.CompletedTask;
                });
                var graphClient = new GraphServiceClient(authProvider);

                //OneDriveにExcelを新規作成
                using (var stream = new MemoryStream())
                {
                    
                    CreateWorkbook(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    var driveItem = await graphClient.Users["O365のユーザID"]
                            .Drive
                            .Root
                            .ItemWithPath("testExcel.xlsx")
                            .Content
                            .Request()
                            .PutAsync<DriveItem>(stream);

                }
                //OneDriveのファイルをリスト
                IDriveItemChildrenCollectionPage items = await graphClient.Users["O365のユーザID"].Drive.Root.Children.Request().GetAsync();

# エクセル作成
```
//エクセル作成
 public static void CreateWorkbook(Stream stream)
        {

            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            var spreadsheetDocument =
                SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            var workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());
            // Add Sheets to the Workbook.
            var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            var sheet = new Sheet()
            { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);

            workbookpart.Workbook.Save();
            // Close the document.
            spreadsheetDocument.Close();
        }
```

# 参照

https://stackoverflow.com/questions/54207620/create-excel-file-through-microsoft-graph-api

https://stackoverflow.com/questions/56152979/using-authprovider-with-ms-sdk-for-graph-calls-in-c-sharp