【问题标题】:Modify google spreadsheet using its public URL and .net library without auth使用其公共 URL 和 .net 库修改 google 电子表格,无需身份验证
【发布时间】:2016-01-22 19:04:33
【问题描述】:
【问题讨论】:
标签:
c#
.net
google-apps-script
google-drive-api
google-spreadsheet-api
【解决方案1】:
这对我有用:
- 在 https://console.developers.google.com 创建一个新的 google 项目并创建一个服务帐户密钥。
- 添加“Drive api”
-
写一些代码
static void DoSheet()
{
var certificate = new X509Certificate2(@"cert.p12", "notasecret", X509KeyStorageFlags.Exportable);
const string scope = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
var credential = new
ServiceAccountCredential(
new ServiceAccountCredential.Initializer("project email")
{
Scopes = new[] { scope }
}.FromCertificate(certificate));
var requestFactory = new GDataRequestFactory("App name");
bool success = credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result;
requestFactory.CustomHeaders.Add($"Authorization: Bearer {credential.Token.AccessToken}");
var service = new SpreadsheetsService("myproject-id") {RequestFactory = requestFactory};
var path = $"https://spreadsheets.google.com/feeds/worksheets/1oKSViNtjtaKjdckJBiIQEZHgbUImnmiNOCQsYpIGdl0/private/full";
var query = new WorksheetQuery(path);
var feed = service.Query(query);
var worksheet = (WorksheetEntry)feed.Entries[0];
var cellQuery = new CellQuery(worksheet.CellFeedLink);
var cellFeed = service.Query(cellQuery);
// Iterate through each cell, printing its value.
foreach (var atomEntry in cellFeed.Entries)
{
var cell = (CellEntry) atomEntry;
if (cell.Title.Text == "A1")
{
cell.InputValue = "200";
cell.Update();
}
else if (cell.Title.Text == "B1")
{
cell.InputValue = "=SUM(A1, 200)";
cell.Update();
}
}
}
这里的诀窍是获取工作表 ID 并在查询 url 中使用它,然后 /private/full