I’m working on a C# application that manages data in Google Sheets using the API. The app can successfully read, write, update and delete data from my spreadsheet. However, when I try to implement column sorting, I keep getting an internal server error (500). Here’s my sorting method:
public bool ApplyColumnSort(
int targetColumnIndex,
int firstRowIndex,
int lastRowIndex,
int leftColumnIndex,
int rightColumnIndex,
string orderDirection,
ref bool hasError)
{
Console.WriteLine("Starting ApplyColumnSort method");
string worksheetName = "Products";
int worksheetId = RetrieveSheetId(_googleSheetsService, _documentId, worksheetName);
BatchUpdateSpreadsheetRequest batchRequest = new BatchUpdateSpreadsheetRequest();
SortRangeRequest sortRequest = new SortRangeRequest();
GridRange rangeToSort = new GridRange();
SortSpec sortSpecification = new SortSpec();
Request apiRequest = new Request();
rangeToSort.SheetId = worksheetId;
rangeToSort.StartRowIndex = firstRowIndex;
rangeToSort.EndRowIndex = lastRowIndex;
rangeToSort.StartColumnIndex = leftColumnIndex;
rangeToSort.EndColumnIndex = rightColumnIndex;
sortRequest.Range = rangeToSort;
sortSpecification.SortOrder = orderDirection;
sortSpecification.DimensionIndex = targetColumnIndex;
if (!hasError)
{
try
{
sortRequest.SortSpecs = new List<SortSpec>() { sortSpecification };
apiRequest.SortRange = sortRequest;
batchRequest.Requests = new List<Request>() { apiRequest };
SpreadsheetsResource.BatchUpdateRequest updateRequest = _googleSheetsService.Spreadsheets.BatchUpdate(
batchRequest, _documentId);
if (updateRequest == null)
{
Console.WriteLine("Failed to create batch update request");
hasError = true;
}
if (!hasError)
{
Console.WriteLine("Processing request...");
BatchUpdateSpreadsheetResponse response = updateRequest.Execute();
Console.WriteLine("Request completed");
}
}
catch (Exception ex)
{
Console.WriteLine("Sorting failed with error: " + ex.Message + ", " + ex.StackTrace);
hasError = true;
}
}
Console.WriteLine("ApplyColumnSort method finished");
return !hasError;
}
I’m calling this method with these parameters:
- targetColumnIndex: 14 (column O)
- firstRowIndex: 1 (skipping header row)
- lastRowIndex: 10536
- leftColumnIndex: 0
- rightColumnIndex: 14
- orderDirection: “ASCENDING”
The Execute() call throws a 500 internal server error with “backendError” as the reason. What could be causing this issue and how can I resolve it?