可以改变Excel单元格的样式吗?

时间:2018-01-25 09:18:25

标签: c# excel microsoft-graph

我想使用 Microsoft Graph SDK 更改Excel单元格的样式。我尝试了以下代码,但它失败,但有例外:

  

“InvalidArgument。参数无效或缺失或格式不正确。”

var range = new WorkbookRange
{
    Format = new WorkbookRangeFormat
    {
        Font = new WorkbookRangeFont { Italic = true }
    }
};
await _client.Me.Drive.Items[fileId]
    .Workbook
    .Worksheets[worksheetId]
    .Range("A1")
    .Request()
    .PatchAsync(range);

我正在使用 nuget 版本1.7.0

1 个答案:

答案 0 :(得分:0)

参考:Range update format docs

这是一个错误。如果我们按预期生成此调用,则调用应如下所示:

var fontPatchObject = new WorkbookRangeFont { Italic = true }
..Worksheets[worksheetId].Range("A1").Format.Font.Request().PatchAsync(fontPatchObject);

以下是解决方法:

var fileId = "yourFileId";
var worksheetId = "yourWorksheetId";
var requestUrl = $@"https://graph.microsoft.com/v1.0/me/drive/items/{fileId}/workbook/worksheets/{worksheetId}/range(address='A1')/format/font";

WorkbookRangeFont font = new WorkbookRangeFont { Italic = true };

string workbookRangeFont = graphClient.HttpProvider.Serializer.SerializeObject(font);

// Create the request message and add the content.
HttpRequestMessage hrm = new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl);
hrm.Content = new StringContent(workbookRangeFont, System.Text.Encoding.UTF8, "application/json");

// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);

// Send the request and get the response.
HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);

if (response.IsSuccessStatusCode)
{
    // Deserialize into WorkbookRangeFont object.
    var content = await response.Content.ReadAsStringAsync();
    WorkbookRangeFont updatedFontObject = graphClient.HttpProvider.Serializer.DeserializeObject<WorkbookRangeFont>(content);
}

Issue #233