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

# sharepointサイトID取得

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/368087/3e2c46d1-e15c-b84e-ae6a-b23b73cf5625.png)

# アクセストークン取得：方法①

            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", accessToken);
                    return Task.CompletedTask;
                });

                var graphClient = new GraphServiceClient(authProvider);

                //sharepointにexcelを新規作成
                using (var stream = new MemoryStream())
                {
                    CreateWorkbook(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    var driveItem = await graphClient
                        .Sites[ "SharepointSiteId入力" ]
                            .Drive
                            .Root
                            .ItemWithPath("testExcel.xlsx")
                            .Content
                            .Request()
                            .PutAsync<DriveItem>(stream);

                    
                 }
             //sharepointファイルをリスト
             IDriveItemChildrenCollectionPage items = await graphClient.Sites[ "SharepointSiteId入力" ].Drive.Root.Children.Request().GetAsync();
```
# エクセル作成
```
//excel作成
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://www.sharepointdiary.com/2018/04/sharepoint-online-powershell-to-get-site-collection-web-id.html#:~:text=To%20Get%20Site%20Collection%20ID,site%2C%20which%20is%20a%20GUID

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

https://learn.microsoft.com/ja-jp/graph/api/resources/onedrive?view=graph-rest-1.0

https://stackoverflow.com/questions/57828956/parsing-json-response-from-httpwebrequest

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/368087/72bcf5fa-9da8-5f48-b56c-d9520d5a9d38.png)