问题
I'm trying to create a request for Google Sheets, but I'm having problems with the sortSpecs method.
var test = new Request()
{
SortRange = new SortRangeRequest()
{
Range = new GridRange()
{
SheetId = 0,
StartRowIndex = 1
},
SortSpecs = new SortSpec()
{
SortOrder = "ASCENDING",
DimensionIndex = 0
}
}
};
When using this, everything works correctly except for the SortSpec. Visual Studio gives the error:
Cannot implicitly convert type 'Google.Apis.Sheets.v4.Data.SortSpec' to System.Collections.Generic.IList' An explicit conversion exists
UPDATE:
There are no more build errors, but now I have another error when executing the code.
List<Data.Request> requests = new List<Data.Request>(); // TODO: Update placeholder value.
Data.SortSpec so = new Data.SortSpec();
so.SortOrder = "ASCENDING";
Data.SortSpec di = new Data.SortSpec();
di.DimensionIndex = 0;
List<Data.SortSpec> ss = new List<Data.SortSpec>();
ss.Add(so);
ss.Add(di);
var test = new Request()
{
SortRange = new SortRangeRequest()
{
Range = new GridRange()
{
SheetId = 0,
StartRowIndex = 1
},
SortSpecs = ss
}
};
requests.Add(test);
The exception given is
Message[Invalid requests[0].sortRange: No sort order specified.] Location[ - ] Reason[badRequest] Domain[global]
回答1:
Per the reference docs, SortSpecs
is a list of items, not a single item. The error message is also saying that (it can't convert SortSpec to an IList). If you want to use a single SortSpec for your sorting specifications, create a list, put that single item in it, and assign SortSpecs
to that list.
回答2:
Looks like you are instantiating 2 new SortSpec objects but you just need 1 object instantiation and assign values to 2 of it's fields "SortOrder" and "DimentionIndex". I had same sheet sorting requirement and I was able to solve it this way:
BatchUpdateSpreadsheetRequest reqbody = new BatchUpdateSpreadsheetRequest();
SortSpec ss = new SortSpec();
ss.DimensionIndex = 1;
ss.SortOrder = "ASCENDING";
GridRange rangetosort = new GridRange();
rangetosort.StartColumnIndex = 0;
rangetosort.EndColumnIndex = 12;
rangetosort.StartRowIndex = 2;
rangetosort.EndRowIndex = totalrows;
rangetosort.SheetId = sheetgid;
SortRangeRequest srr = new SortRangeRequest();
srr.Range = rangetosort;
IList<SortSpec> sortspecs = new List<SortSpec>();
sortspecs.Add(ss);
srr.SortSpecs = sortspecs;
Request req1 = new Request();
req1.SortRange = srr;
IList<Request> req2 = new List<Request>();
req2.Add(req1);
reqbody.Requests = req2;
SpreadsheetsResource.BatchUpdateRequest sortreq = sheetsrv1.Spreadsheets.BatchUpdate(reqbody, spid);
try
{
sortreq.Execute();
Console.WriteLine("Sorting Operation successfull");
}
catch(Exception ex6)
{
Console.WriteLine(ex6.Message);
}
来源:https://stackoverflow.com/questions/45340136/google-sheets-sortspecs