0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-10-20

sharepointサイトID取得

image.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();
        }

参考

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?