使用其公共URL和.net库修改谷歌电子表格而不使用身份验证

时间:2016-01-22 19:04:33

标签: c# .net google-apps-script google-drive-api google-spreadsheet-api

我有一个与我共享的Google电子表格网址,其中包含“每个有链接都可以编辑”权限的人 我需要能够将smth放在它的单元格中,但我不知道该怎么做,谷歌文档对此没有帮助。 有任何想法吗? Google文档共享网址为https://docs.google.com/spreadsheets/d/1oKSViNtjtaKjdckJBiIQEZHgbUImnmiNOCQsYpIGdl0/edit?usp=sharing

我可以通过网络浏览器对它做任何事情,所以我可能可以用.net库做到这一点?

1 个答案:

答案 0 :(得分:0)

这对我有用:

  1. https://console.developers.google.com创建一个新的Google项目并创建一个服务帐户密钥。
  2. 添加“Drive api”
  3. 写一些代码

    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();
            }
        }
    }
    
  4. 这里的技巧是获取工作表ID并在之后使用/ private / full在查询网址中使用它