【发布时间】:2020-08-24 10:31:47
【问题描述】:
我目前正在使用正则表达式在 url 中查找 google sheet 的“SpreadSheetId”和“SheetId”。我可以找到带有“SpreadSheetId”和工作表名称的文件,但是...... 我不明白为什么我不能使用“SheetId”来找到它。它仅适用于工作表的确切名称。
Google API V4:https://developers.google.com/sheets/api/quickstart/dotnet
如何找到带有 sheetId 而不是名称的工作表。
UserCredential credential;
using (var stream =
new FileStream("code_secret_client.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define request parameters.
//1HtsjLDHo9oaNqeSPKt8YRCEKg5lfa9ONzytJm_6thS4
//find regex
Regex RxSpreadSheetId = new Regex(@"/spreadsheets/d/([a-zA-Z0-9-_]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Regex RxSheetId = new Regex(@"[#&]gid=([0-9]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//
string URL = string.Copy(textBox2.Text);
Match MatchSpreadSheetId = RxSpreadSheetId.Match(URL);
Match MatchSheetId = RxSheetId.Match(URL);
String SpreadSheetId = MatchSpreadSheetId.Groups[1].Value;
String SheetId = MatchSheetId.Groups[1].Value;
String range = SheetId + "!A2:B";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(SpreadSheetId, range);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
// Print columns A and E, which correspond to indices 0 and 4.
Console.WriteLine("{0}, {1}", row[0], row[1]);
richTextBox1.Text = (string)row[1];
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
【问题讨论】:
标签: c# .net excel google-sheets google-sheets-api