Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用谷歌应用程序脚本API(C#)编辑谷歌工作表时出现问题_C#_.net_Api_Google Apps Script_Google Sheets - Fatal编程技术网

使用谷歌应用程序脚本API(C#)编辑谷歌工作表时出现问题

使用谷歌应用程序脚本API(C#)编辑谷歌工作表时出现问题,c#,.net,api,google-apps-script,google-sheets,C#,.net,Api,Google Apps Script,Google Sheets,我正在尝试使用google应用程序脚本API运行一个脚本,该API将更新google工作表上的值。我已经测试了google脚本,它与工作表正常工作,我已经使用google app script API测试了与脚本的连接,连接成功(我可以成功地记录通过C#程序传递到脚本中的变量)。当我通过C#应用程序调用脚本时,脚本运行并记录传入的变量,但是google工作表没有更改,即使通过脚本编辑器运行脚本确实与google工作表交互。我已将驱动器和电子表格脚本添加到我的作用域中。为什么在使用C#应用程序时没

我正在尝试使用google应用程序脚本API运行一个脚本,该API将更新google工作表上的值。我已经测试了google脚本,它与工作表正常工作,我已经使用google app script API测试了与脚本的连接,连接成功(我可以成功地记录通过C#程序传递到脚本中的变量)。当我通过C#应用程序调用脚本时,脚本运行并记录传入的变量,但是google工作表没有更改,即使通过脚本编辑器运行脚本确实与google工作表交互。我已将驱动器和电子表格脚本添加到我的作用域中。为什么在使用C#应用程序时没有与google表单交互

C#应用程序:
使用Google.api.Auth.OAuth2;
使用Google.api.Script.v1;
使用Google.api.Script.v1.Data;
使用Google.api.Sheets.v4;
使用Google.api.Sheets.v4.Data;
使用Google.api.Services;
使用Google.api.Util.Store;
使用制度;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
名称空间PPR
{
古格里皮类
{
//如果修改这些作用域,请删除以前保存的凭据
//位于~/.credentials/script-dotnet-quickstart.json
静态字符串[]作用域={”https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets" };
静态字符串ApplicationName=“谷歌应用程序脚本执行API.NET快速启动”;
公共服务
{
用户凭证;
使用(var)流=
新的文件流(“client_secret.json”、FileMode.Open、FileAccess.Read))
{
字符串credPath=System.Environment.GetFolderPath(
系统、环境、专用文件夹、个人);
credPath=Path.Combine(credPath,“.credentials/script dotnet quickstart.json”);
凭证=GoogleWebAuthorizationBroker.AuthorizationAsync(
GoogleClientSecrets.Load(stream.Secrets),
范围,
“用户”,
取消令牌。无,
新文件数据存储(credPath,true))。结果;
Console.WriteLine(“凭证文件保存到:”+credPath);
}
//创建谷歌应用程序脚本执行API服务。
字符串scriptId=“MPD2B-0a8Q2KsDHoHVPh1HVhXBvIk9FTo”;
var service=new ScriptService(new BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=ApplicationName,
});
//创建一个执行请求对象。
ExecutionRequest=新的ExecutionRequest();
//request.Function=“updateCells”;
request.Function=“callWeeklyHours”;
request.DevMode=true;
IList值=新列表();
添加(“临时项目”);
价值。添加(“本”);
//参数=值;
ScriptsResource.RunRequest runReq=
service.Scripts.Run(请求,scriptId);
尝试
{
//发出API请求。
操作op=runReq.Execute();
}
catch(Google.GoogleApiException e)
{
//API在执行脚本之前遇到问题
//开始执行。
WriteLine(“调用API时出错:\n{0}”,e);
}
Console.Read();
}
}
}
谷歌脚本:
函数callWeeklyHours()
{
updateCells(“新项目”、“本”);
}
函数更新cells(projectName,projectManager)
{  
Logger.log(projectName+,'+projectManager);
var ui=SpreadsheetApp.getUi();
var ss=SpreadsheetApp.getActiveSpreadsheet();
var foundPage=false;

对于(var i=0;这可能有助于进行故障排除。我看到您正在调用SpreadsheetApp.getActiveSheet()。是否存在有效的“活动工作表”在这种情况下?也许你需要通过文档id显式引用你的电子表格。啊,那可能是,谢谢!我对谷歌脚本非常陌生-你能告诉我如何引用谷歌工作表中的页面,以便我可以使用文档id更改值吗?我尝试了openById函数,但仍然没有成功正确连接。函数如下:请参阅顶部的注释以确定要使用的id值。很好,我已将其连接到工作表并成功添加了新页面!感谢帮助!:)如果你不介意的话,我还有最后一个问题:是否可以打开google工作表并通过c#app与之交互?我已经成功地通过脚本将应用程序连接到google工作表,但我的总体目标是在google工作表上弹出一个UI提示,允许用户键入单元格以存储数据。这可能吗?
C# APP:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Script.v1;
using Google.Apis.Script.v1.Data;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PPR
{
    class googleAPI
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/script-dotnet-quickstart.json
        static string[] Scopes = { "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets" };
        static string ApplicationName = "Google Apps Script Execution API .NET Quickstart";

        public googleAPI()
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/script-dotnet-quickstart.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 Apps Script Execution API service.
            string scriptId = "MPD2B-0a8Q2KsDHoHVPh1HVhXBvIk9FTo";
            var service = new ScriptService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Create an execution request object.
            ExecutionRequest request = new ExecutionRequest();
            //request.Function = "updateCells";
            request.Function = "callWeeklyHours";
            request.DevMode = true;

            IList<object> values = new List<object>();
            values.Add("tempProj");
            values.Add("Ben");
            //request.Parameters = values;

            ScriptsResource.RunRequest runReq =
                    service.Scripts.Run(request, scriptId);

            try
            {
                // Make the API request.
                Operation op = runReq.Execute();
            }
            catch (Google.GoogleApiException e)
            {
                // The API encountered a problem before the script
                // started executing.
                Console.WriteLine("Error calling API:\n{0}", e);
            }
            Console.Read();
        }
    }
}

Google Script:

function callWeeklyHours()
{
    updateCells("New Project","Ben");
}

function updateCells(projectName, projectManager)
{  
    Logger.log(projectName + ', ' + projectManager);
    var ui = SpreadsheetApp.getUi();  
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var foundPage = false;
    for(var i = 0; i<sheetnames().length; i++){    
        if(("" +sheetnames()[i]).split(" ")[0] == projectManager){
            ss.setActiveSheet(ss.getSheetByName(sheetnames()[i]));
            foundPage = true;
            break;
        }
    }
    //SpreadsheetApp.getActiveSheet().getRange("A1").setValue(projectName);


    if(foundPage == false){
        ui.alert('Project Manager Sheet Does Not Exist', 'The project manager in charge of this project has not created a sheet (a sheet named ' + projectManager + ' does not exist). Project information will not be entered.', ui.ButtonSet.OK)
        return;
    }
    var response = ui.prompt('Enter New Project', 'Store project name in which 
cell?', ui.ButtonSet.OK);
    try{


  SpreadsheetApp.getActiveSheet().getRange(response.getResponseText()).setValue(projectName);
    }
    catch (e){
    var invalidInput = ui.alert('Invalid Cell Input', 'The cell name was invalid - project information was not entered', ui.ButtonSet.OK)
    }    

}

function sheetnames() { // Contributed by ahab facit, 2011
    var out = new Array()
    var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
    for (var i=0 ; i<sheets.length ; i++) out.push( [ sheets[i].getName() ] )
    return out  
}