首页 > 解决方案 > Google Sheets API CopyPasteRequest 无效

问题描述

我只是想将电子表格中第一张工作表中的一系列单元格复制到第二张工作表中。此代码运行没有错误,但实际工作表上没有任何反应。

我在下面缺少什么?

 var spreadSheet = service.Spreadsheets.Get(spreadsheetId).Execute();
 int? sourceSheetId = spreadSheet.Sheets[0].Properties.SheetId;
 int? targetSheetId = spreadSheet.Sheets[1].Properties.SheetId;

 // Copy in the current data from the "Training Data" tab
 CopyPasteRequest copyReq = new CopyPasteRequest()
 {
     Source = new GridRange() {  SheetId = sourceSheetId, StartColumnIndex = 0, 
         StartRowIndex = 1, EndColumnIndex = 0, EndRowIndex = 3000 },
     Destination = new GridRange() { SheetId = targetSheetId, 
         StartColumnIndex = 0, StartRowIndex = 1, EndColumnIndex = 0, EndRowIndex = 3000 },
     PasteType = "PASTE_VALUES",
     PasteOrientation = "NORMAL"
 };

 var copyResource = new BatchUpdateSpreadsheetRequest() { Requests = new List<Request>() };
 var reqCopy = new Request() { CopyPaste = copyReq };
 copyResource.Requests.Add(reqCopy);

 var result = service.Spreadsheets.BatchUpdate(copyResource, spreadsheetId).Execute();
 // no errors, and result object is populated -- but nothing appears in the target sheet

标签: c#google-sheetsgoogle-api

解决方案


根据我的理解,您正在尝试将源工作表的 A 列复制到目标工作表的 A 列。

您的请求没有效果的原因是您EndColumnIndexGridRange中不正确,EndColumnIndex并且EndRowIndex被排除在要复制的范围内。

endRowIndex

范围的结束行(不包括),如果无界则不设置。

结束列索引

范围的结束列(不包括),如果无界则不设置。


例子:

我想复制Sheet1!A1:A10Sheet2!A1:A10

在此处输入图像描述

请求正文:

{
  "requests": [
    {
      "copyPaste": {
        "source": {
          "sheetId": 0,
          "startRowIndex": 0,
          "startColumnIndex": 0,
          "endColumnIndex": 1,
          "endRowIndex": 10
        },
        "destination": {
          "sheetId": 133812xxxx,
          "startRowIndex": 0,
          "startColumnIndex": 0,
          "endColumnIndex": 1,
          "endRowIndex": 10
        },
        "pasteOrientation": "NORMAL",
        "pasteType": "PASTE_NORMAL"
      }
    }
  ]
}
  • 工作表索引从零开始
  • endColumnIndex设置为 1(不包括 B 列)
  • endRowIndex设置为 10(第 11 行除外)

输出:

在此处输入图像描述


推荐阅读