如何使用Microsoft图形API在Excel单元格中添加公式?

时间:2018-04-13 16:14:59

标签: c# excel microsoft-graph

我正在尝试使用Microsoft Graph的Excel API向Excel中的单元格添加内容。我可以使用PATCH方法添加内容,但是当我尝试添加公式时,它的行为不像公式。如果我传递'formulas': '=sum(2+2)'之类的东西,它就不会表现得如此。

我得到的结果是剪辑: enter image description here

这可行吗?

这是我的代码:

//Set up workbook and worksheet endpoints
var workbookEndpoint = "https://graph.microsoft.com/v1.0/me/drive/items/" +
    fileId + "/workbook";

var worksheetsEndpoint = workbookEndpoint + "/worksheets";

var patchMethod = new HttpMethod("PATCH");

var summaryTableRowJson = "{" +
    "'formulas': '=sum(2+2)'" +
    "}";

var colNamePatchBody = new StringContent(summaryTableRowJson);
colNamePatchBody.Headers.Clear();
colNamePatchBody.Headers.Add("Content-Type", "application/json");

var colNameRequestMessage = new HttpRequestMessage(patchMethod, worksheetsEndpoint +
    "('" + worksheetName + "')/range(address='Sheet1!B2')")
{
    Content = colNamePatchBody
};

var colNameResponseMessage = await client.SendAsync(colNameRequestMessage);

1 个答案:

答案 0 :(得分:2)

您需要通过formulas而非values属性传入此内容:

{
  "formulas" : "=sum(2+2)"
}

您还应该考虑使用Microsoft Graph Client Library for .NET而不是滚动自己的原始HTTP调用。随着时间的推移,它将为您节省大量的麻烦。它还可以产生更清晰的代码:

await graphClient.Me
    .Drive
    .Items["id"]
    .Workbook
    .Worksheets["Sheet1"]
    .Range("C12")
    .Request()
    .PatchAsync(new WorkbookRange()
    {
        Formulas = JArray.Parse(@"[['=2.2']]")
    });