I'm trying to protect a range in a google sheet using the sheets API (v4) in a .NET project.
I've been able to create a sheet and move it to the desired folder using the Drive API, but now I need to protect a certain range. I'm unsure how to form the request. I'm thinking I may need to use the batchUpdateRequest - but not entirely sure.
I have this so far:
var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile).CreateScoped(Google.Apis.Sheets.v4.SheetsService.ScopeConstants.Spreadsheets);
var service = new Google.Apis.Sheets.v4.SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
var body = new Google.Apis.Sheets.v4.Data.Request();
body.AddProtectedRange.ProtectedRange.ProtectedRangeId(){
};
var request = service.Spreadsheets.BatchUpdate(body, fileId);
Any help would be greatly appreciated. Thanks!
You can use this code to protect a range:
var spreadsheetId = "spreadsheet id"; //can get from sheet url
var sheetId = "sheet id";
var range = "A1:B10";
var request = new BatchUpdateSpreadsheetRequest()
{
Requests = new List<Request>
{
new()
{
AddProtectedRange = new AddProtectedRangeRequest
{
ProtectedRange = new ProtectedRange
{
Range = new GridRange
{
SheetId = sheetId,
StartRowIndex = 0,
EndRowIndex = 9,
StartColumnIndex = 0,
EndColumnIndex = 1
},
Description = "Protected Range",
WarningOnly = false
}
}
}
}
};
service.Spreadsheets.BatchUpdate(request, spreadsheetId).Execute();
AddProtectedRangeRequest docs
Related
I am trying to use the c# Google Sheets API for inputting information into my Google Sheets via the code below, but it is only inputting as rows and I would like to input it as columns instead. Is there a way to do this?
valueRange.Values = new List<IList<object>> { objectList };
appendRequest = service.Spreadsheets.Values.Append(valueRange, SpreadsheetId, range);
appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
appendResponse = appendRequest.Execute();
I fixed your code in the below. Seems your valueRange.Values convert is incorrect.
public static AppendValuesResponse InsertColumnLine(this SheetsService service, string spreadsheetId, string range, params object[] columnValues)
{
// convert columnValues to columList
var columList = columnValues.Select(v => new List<object> { v });
// Add columList to values and input to valueRange
var values = new List<IList<object>>();
values.AddRange(columList.ToList());
var valueRange = new ValueRange()
{
Values = values
};
// Create request and execute
var appendRequest = service.Spreadsheets.Values.Append(valueRange, spreadsheetId, range);
appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
return appendRequest.Execute();
}
Use the extension InsertColumnLine method.
// Sample!A1 => Sample is workseet name, A1 cell feild
_sheetsService.InsertColumnLine(_chickenOptions.Debug.SpreadSheetId, "Sample!A1", 1, 2, 3, 4, 5);
See the result. I hope it will help you.
I have a code that its purpose is to rename a specific sheet, but when executing the BatchUpdate and the code is crached, does anyone have any ideas?
public void UpdateSheetName(string sheetName,string newSheetName)
{
//get sheet id by sheet name
Spreadsheet spr = service.Spreadsheets.Get(SpreadsheetId).Execute();
Sheet sh = spr.Sheets.Where(s => s.Properties.Title == sheetName).FirstOrDefault();
int sheetId = (int)sh.Properties.SheetId;
BatchUpdateSpreadsheetRequest bussr = new BatchUpdateSpreadsheetRequest();
var request = new Request()
{
UpdateSpreadsheetProperties= new UpdateSpreadsheetPropertiesRequest(){
Properties=new SpreadsheetProperties()
{
Title= newSheetName,
},
Fields ="title"
}
};
bussr.Requests = new List<Request>();
bussr.Requests.Add(request);
var bur = service.Spreadsheets.BatchUpdate(bussr, SpreadsheetId);
bur.Execute();
}
Error Message:
Invalid value at 'requests[0]' (oneof), oneof field 'kind' is already set. Cannot set 'updateSpreadsheetProperties' [400]
I found the problem, the problem was that I had used the wrong class, use UpdateSpreadsheetProperties instead of UpdateSheetPropertiesRequest
var request = new Request()
{
UpdateSheetProperties =new UpdateSheetPropertiesRequest {
Properties=new SheetProperties()
{
Title=newName,
SheetId=sheetId
},
Fields = "Title"
}
};
I am trying to insert rows in google sheet with c# console application using Google Sheets API v4. I am able to insert row with below code but not able to insert on top.
I want that every row inserted should be inserted on top and other existing row should shift down.
SpreadsheetsResource.ValuesResource.UpdateRequest request =
service.Spreadsheets.Values.Update(new ValueRange() { Values = values }, spreadsheetId, newRange);
request.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
var response = request.Execute();
I tried following and it worked for me:-
InsertDimensionRequest insertRow = new InsertDimensionRequest();
insertRow.Range = new DimensionRange()
{
SheetId = MySheetID,
Dimension = "ROWS",
StartIndex = 1,
EndIndex = 2
};
PasteDataRequest data = new PasteDataRequest
{
Data = string.Join(",", values[0]),
Delimiter = ",",
Coordinate = new GridCoordinate
{
ColumnIndex = 0,
RowIndex = 1,
SheetId = MySheetID
},
};
BatchUpdateSpreadsheetRequest r = new BatchUpdateSpreadsheetRequest()
{
Requests = new List<Request>
{
new Request{ InsertDimension = insertRow },
new Request{ PasteData = data }
}
};
BatchUpdateSpreadsheetResponse response1 = service.Spreadsheets.BatchUpdate(r, spreadsheetId).Execute();
Thanks #tehhowch
I have to copy existing sheet and rename it. And I cannot find any info how to rename the sheet via Google sheets API v4.
For now I have:
var defaultSheet = service.Spreadsheets
.Get(spreadsheetKey)
.Execute().Sheets
.First(x => x.Properties.Title.Equals("Default sheet"));
var newSheet = Service.Spreadsheets.Sheets.CopyTo(
new CopySheetToAnotherSpreadsheetRequest { DestinationSpreadsheetId = spreadsheetKey },
spreadsheetKey,
(int)defaultSheet.Properties.SheetId);
I hope anyone has any idea how to do it.
Thanks in advance!
Solution (how to copy sheet with specified name):
var defSheet = Service.Spreadsheets.Get(baseUrl).Execute().Sheets.First(x => x.Properties.Title.Equals("OldSheet"));
var newSheet = new Request
{
DuplicateSheet = new DuplicateSheetRequest
{
SourceSheetId = defSheet.Properties.SheetId,
NewSheetName = "NewSheet",
InsertSheetIndex = 1
}
};
var y = new BatchUpdateSpreadsheetRequest { Requests = new List<Request> { newSheet } };
Service.Spreadsheets.BatchUpdate(y, baseUrl).Execute();
Can one please help me in how to access the Google Spread Sheet Data using there Google Sheet API using oAuth 2.0 also when the sheet is accessed how to insert/add data there online
In .NET C#?
I found this Link but it is using oauth 1 and only accessing the data
Please provide an example or link
I found the following code that access and write values in columns :
string CLIENT_ID = "***";
string CLIENT_SECRET = "***";
string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
Console.WriteLine(authorizationUrl);
Console.WriteLine("Please visit the URL above to authorize your OAuth "
+ "request token. Once that is complete, type in your access code to "
+ "continue...");
parameters.AccessCode = Console.ReadLine();
OAuthUtil.GetAccessToken(parameters);
string accessToken = parameters.AccessToken;
Console.WriteLine("OAuth Access Token: " + accessToken);
GOAuth2RequestFactory requestFactory =
new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;
SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = service.Query(query);
//foreach (SpreadsheetEntry entry in feed.Entries)
//{
// Console.WriteLine(entry.Title.Text);
//}
SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[0];
Console.WriteLine(spreadsheet.Title.Text);
// Get the first worksheet of the first spreadsheet.
// TODO: Choose a worksheet more intelligently based on your
// app's needs.
WorksheetFeed wsFeed = spreadsheet.Worksheets;
WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0];
// Define the URL to request the list feed of the worksheet.
AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
// Fetch the list feed of the worksheet.
ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
ListFeed listFeed = service.Query(listQuery);
CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink);
CellFeed cellFeed = service.Query(cellQuery);
CellEntry cellEntry = new CellEntry(1, 1, "firstname");
cellFeed.Insert(cellEntry);
cellEntry = new CellEntry(1, 2, "lastname");
cellFeed.Insert(cellEntry);
cellEntry = new CellEntry(1, 3, "age");
cellFeed.Insert(cellEntry);
cellEntry = new CellEntry(1, 4, "height");
cellFeed.Insert(cellEntry);
// Create a local representation of the new row.
ListEntry row = new ListEntry();
row.Elements.Add(new ListEntry.Custom() { LocalName = "firstname", Value = "Joe" });
row.Elements.Add(new ListEntry.Custom() { LocalName = "lastname", Value = "Smith" });
row.Elements.Add(new ListEntry.Custom() { LocalName = "age", Value = "26" });
row.Elements.Add(new ListEntry.Custom() { LocalName = "height", Value = "176" });
// Send the new row to the API for insertion.
service.Insert(listFeed, row);