简体   繁体   中英

Create excel file through Microsoft Graph API

Does anyone know how to create excel and ppt files through the MS Graph API? We're trying to leverage the MS Graph API to create word/excel/ppt files on a button click and while we found how to create word files, the excel and powerpoint files created are corrupted even with a success response from the api. The end point below works for the word files. We've been just working with the graph api explorer ( https://developer.microsoft.com/en-us/graph/graph-explorer# ) for now. Any help would be appreciated!

POST https://graph.microsoft.com/v1.0/drives/{Drive ID}/root/children/ 

Request Body:
{
  "name": "FileTest6.docx",
  "file":{
  }
}

PowerPoint files

PowerPoint files could be created via DriveItem upload endpoint, for example:

PUT https://graph.microsoft.com/v1.0/me/drive/root:/sample.pptx:/content

or

POST https://graph.microsoft.com/v1.0/me/drive/root/children
{
  "name": "Sample.pptx",
  "file":{ }
}

Excel files

With excel files the situation is a bit different since the content of the excel file to be uploaded needs to be provided explicitly .

For ASP.NET Core application the following solution could be considered:

C# example

using (var stream = new MemoryStream())
{
    CreateWorkbook(stream);
    stream.Seek(0, SeekOrigin.Begin);
    var driveItem = await graphClient.Me
            .Drive
            .Root
            .ItemWithPath("SampleWorkbook1.xlsx")
            .Content
            .Request()
            .PutAsync<DriveItem>(stream);
    }

where

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM