使用带有Microsoft Graph API的Sharepoint文档库处理Excel文件

时间:2017-08-16 13:39:58

标签: c# office365 microsoft-graph sharepoint-online

我下载并自定义了这个项目asp mvc todo sample。这是正常工作没有任何问题onedrive excel文件/项目。但我必须在线使用office 365 sharepoint。 我可以使用服务点获取文件ID,如下所示:

var serviceEndpoint = "https://graph.microsoft.com/beta/sites/mydomain.sharepoint.com:/foa/bd:/lists/Budget/items";

但我不确定如何使用Sharepoint定义工作簿端点URL以更新/操作相同的Excel文件数据。当前工作簿端点URL如下(不起作用):

var workbookEndpoint = "https://graph.microsoft.com/beta/sites/mydomain.sharepoint.com:/foa/bd:/lists/Budget/items/" + fileId + "/workbook";

我在Sharepoint上更新excel文件中的单元格值的完整方法,如下所示:

public static async Task UpdateExcelCellValue_Sharepoint(string accessToken, string cellAddress, string val)
    {
        string worksheetName = "Parameters";
        var serviceEndpoint = "https://graph.microsoft.com/beta/sites/mydomain.sharepoint.com:/foa/bd:/lists/Budget/items";
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        var filesResponse = await client.GetAsync(serviceEndpoint + "?$select=name,id");
        if (filesResponse.IsSuccessStatusCode)
        {
            var filesContent = await filesResponse.Content.ReadAsStringAsync();
            JObject parsedResult = JObject.Parse(filesContent);
            foreach (JObject file in parsedResult["value"])
            {
                var name = (string)file["id"];
                if (name.Contains("173"))
                {
                    fileId = (string)file["id"];
                    break;
                }
            }
        }
        else
        {
            //Handle failed response
        }
        //Set up workbook and worksheet endpoints
        var workbookEndpoint = "https://graph.microsoft.com/beta/sites/mydomain.sharepoint.com:/foa/bd:/lists/Budget/items/" + fileId + "/workbook";
        var worksheetsEndpoint = workbookEndpoint + "/worksheets";
        var patchMethod = new HttpMethod("PATCH");
        var summaryTableRowJson = "{" +
                "'values': '" + val + ".csv'" +
            "}";
        var colNamePatchBody = new StringContent(summaryTableRowJson);
        colNamePatchBody.Headers.Clear();
        colNamePatchBody.Headers.Add("Content-Type", "application/json");
        var colNameRequestMessage = new HttpRequestMessage(patchMethod, worksheetsEndpoint +
            "('" + worksheetName + "')/range(address='Parameters!B2')")
        { Content = colNamePatchBody };
        var colNameResponseMessage = await client.SendAsync(colNameRequestMessage);
    }

1 个答案:

答案 0 :(得分:0)

现在应该可以了。例如,这是一条有用的路径:

https://graph.microsoft.com/beta/sites/{tenant-name}.sharepoint.com/lists/{id}/drive/root:/Book.xlsx:/workbook。这是其中一种可能性。

您始终可以尝试使用ID替换路径以查看其是否有效(两者都应该有效)。