在Google表格中的单元格中添加注释C#

时间:2020-03-19 12:58:54

标签: c# google-sheets-api

是否可以使用Google在单元格中添加注释? Apis.Sheets.v4?

在python中似乎可行:Is it possible to use the Google Spreadsheet API to add a comment in a cell?,但我没有成功将其复制到c#,Insert a comment in a Google Sheet with google-sheets-api描述了如何使用https调用添加它,但我宁愿使用google c#可能的话,我自己开始发送HTTP调用。 如果有人知道专有技术,或者可以向我指出一个可行的示例,那将是巨大的帮助。

先谢谢了。

使用Rafa Guillermos的建议,我使它起作用。

        public async void AddNote(string sheet, int column, int row, int sheetId, string noteMessage)
        {
            await Task.Delay(1);

            var requests = new List<Request>();


            // Grid range for a single cell, end column, and row have to be +1, otherwise, sheet throws error trying to write outside bounds.
            var gridRange = new Google.Apis.Sheets.v4.Data.GridRange
            {
                EndColumnIndex = column + 1, StartColumnIndex = column, EndRowIndex = row + 1, StartRowIndex = row, SheetId = sheetId
            };

            // Building a request for update cells.
            var request = new Google.Apis.Sheets.v4.Data.Request();
            request.UpdateCells = new Google.Apis.Sheets.v4.Data.UpdateCellsRequest();
            request.UpdateCells.Range = gridRange;
            request.UpdateCells.Fields = "note";
            request.UpdateCells.Rows = new List<Google.Apis.Sheets.v4.Data.RowData>();
            request.UpdateCells.Rows.Add(new Google.Apis.Sheets.v4.Data.RowData());
            request.UpdateCells.Rows[0].Values = new List<Google.Apis.Sheets.v4.Data.CellData>();
            request.UpdateCells.Rows[0].Values.Add(new Google.Apis.Sheets.v4.Data.CellData());
            request.UpdateCells.Rows[0].Values[0].Note = noteMessage;

            requests.Add(request);

            var requestBody = new Google.Apis.Sheets.v4.Data.BatchUpdateSpreadsheetRequest();
            requestBody.Requests = requests;

            var service = _authenticatorService.GetSheetsService(new[] { SheetsService.Scope.Spreadsheets} );

            var batchRequest = service.Spreadsheets.BatchUpdate(requestBody, _spreadsheetId);
            batchRequest.Execute();
        }

_authenticatorService提供经过身份验证的工作表服务。

1 个答案:

答案 0 :(得分:0)

答案:

与python完全相同,您需要在C#中将注释构建为批处理请求。

代码段:

您需要以列表形式构建数据请求:

List<Data.Request> requests = new List<Data.Request>();

并将值分配给批次的请求正文:

Data.BatchUpdateSpreadsheetRequest requestBody = new Data.BatchUpdateSpreadsheetRequest();
requestBody.Requests = requests;

在构建请求对象之前:

SpreadsheetsResource.BatchUpdateRequest request = sheetsService.Spreadsheets.BatchUpdate(requestBody, spreadsheetId);

并执行请求:

Data.BatchUpdateSpreadsheetResponse response = request.Execute();

更多信息:

您可以在页面here的底部阅读带有C#示例代码的spreadsheets.batchUpdate here

可以找到here的请求资源的JSON表示,其结构与answer you linked here相同。

希望对您有帮助!

参考文献:

相关问题