英文:
Sort range based on a column using a google sheets API in Java
问题
以下是翻译好的部分:
我已经成功使用我的Java代码检索和更新数据到我的Google Sheets电子表格中。
我正在尝试在更新后对数据进行排序,但出现了500内部服务器错误,想知道我发送了什么错误。我试图升序排序范围 "E1:I1000"。
这是我的代码:
Sheets sheetsService = GoogleAuthorizeUtil.getSheetsService("worktest");
BatchUpdateSpreadsheetRequest busReq = new BatchUpdateSpreadsheetRequest();
SortRangeRequest srr = new SortRangeRequest();
GridRange gr = new GridRange();
SortSpec ss = new SortSpec();
Request req = new Request();
gr.setSheetId(0);
gr.setStartRowIndex(1);
gr.setEndRowIndex(1000);
gr.setStartColumnIndex(5);
gr.setEndColumnIndex(10);
srr.setRange(gr);
ss.setSortOrder("ASCENDING");
ss.setDimensionIndex(1);
srr.setSortSpecs(Arrays.asList(ss));
req.setSortRange(srr);
busReq.setRequests(Arrays.asList(req));
sheetsService.spreadsheets().batchUpdate(googleID, busReq).execute();
在我尝试对其进行排序的方式中是否有任何问题?
英文:
I have my Java code working fine with retrieving and updating data to my Google Sheets spreadsheet.
I am trying to sort the data after updating, and getting a 500 Internal Server Error and was wondering what I am sending wrong. I am trying to ASCENDING sort Range "E1:I1000"
Here is my code:
Sheets sheetsService = GoogleAuthorizeUtil.getSheetsService("worktest");
BatchUpdateSpreadsheetRequest busReq = new BatchUpdateSpreadsheetRequest();
SortRangeRequest srr = new SortRangeRequest();
GridRange gr = new GridRange();
SortSpec ss = new SortSpec();
Request req = new Request();
gr.setSheetId(0);
gr.setStartRowIndex(1);
gr.setEndRowIndex(1000);
gr.setStartColumnIndex(5);
gr.setEndColumnIndex(10);
srr.setRange(gr);
ss.setSortOrder("ASCENDING");
ss.setDimensionIndex(1);
srr.setSortSpecs(Arrays.asList(ss));
req.setSortRange(srr);
busReq.setRequests(Arrays.asList(req));
sheetsService.spreadsheets().batchUpdate(googleID, busReq).execute();
Is there anything wrong in how I am trying to sort this?
答案1
得分: 3
你正在尝试按列E:I
来排序,以列B
为依据 - 这是不可能的!
更多信息:
在你的代码中,你将要排序的数据的dimensionIndex
设置为1
的值。这不是你要排序的数据的第二列,而是你整个电子表格的第二列。
这在SortSpec文档中并不明确,但可以从Google在数据操作文档中提供的示例中推断出来。
代码修复:
要解决这个问题,你只需要更改传递给setDimensionIndex
的值:
ss.setDimensionIndex(1)
改为:
ss.setDimensionIndex(6)
参考:
- Method: spreadsheets.batchUpdate | Sheets API | Google Developers
- Data Operations | Sheets API | Google Developers
- Sheets API | Google Developers - SortSpec
英文:
Answer:
You are trying to sort columns E:I
by column B
- this is not possible!
More Information:
In your code, you are setting the dimensionIndex
for which to sort the data by, to the value of 1
. This isn't the second column of the data you want to sort, but the second column of your whole spreadsheet.
This isn't clear from the SortSpec documentation, but can be inferred from the example provided by Google in the Data Operations documentation
Code Fix:
All you need to do to sort this is change the value passed to setDimensionIndex
:
ss.setDimensionIndex(1)
change to:
ss.setDimensionIndex(6)
References:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论