将数据从C#附加到Google Sheet,称为SqlCommand

时间:2018-05-16 15:14:31

标签: c# google-sheets google-api

我从基础开始,学习了如何从我的程序中向Google Sheet插入一些固定的行,现在我一直试图找出如何从SQL附加输出。我有一个调用存储过程的C#程序,或者它可以执行select * from table。只需尝试将该选择的结果/输出插入Google表格。我发现的每个例子都是处理硬编码的固定行和列。我的选择产生少于2000行的输出。感谢帮助!

namespace CS_Gsheet1
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        //static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
        //static string ApplicationName = "Google Sheets API .NET Quickstart";
        static string[] Scopes = { SheetsService.Scope.Spreadsheets };
        static string ApplicationName = "Test3"; 

        static void Main(string[] args)
        {
            var service = AuthorizeGoogleApp();

            String spreadsheetId = "sheetIDstring"; 

            // Write to specified sheet
            String writeRange = "Sheet1!A1:K";
            ValueRange valueRange = new ValueRange { MajorDimension = "ROWS" };

            IList<object> dataList = new List<object>();

            using(SqlConnection myConnection = new SqlConnection("connectionstring"))
            {
                myConnection.Open();

                using(SqlCommand cmd = new SqlCommand("storedproc-selectsmultiplecolumnsandrows", myConnection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    using(SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            // dataList.Add(reader.GetString(0));
                            // dataList.Add(reader.GetValue(0));
                            IList<IList<Object>> values = new List<IList<Object>>();
                            values.Add(dataList);
                        }
                    }
                }
            }

            // Data is accessible through the DataReader object here.
            ValueRange valueDataRange = new ValueRange() { MajorDimension = "ROWS" };

            valueDataRange.Values = new List<IList<object>> { dataList };

            int c = dataList.Count;
            Console.WriteLine("dataList Count {0}", c);

            for (int i = 0; i < c; i++)
            {
                // API to append data to sheet
                SpreadsheetsResource.ValuesResource.AppendRequest appendRequest = service.Spreadsheets.Values.Append(valueDataRange, spreadsheetId, writeRange);
                appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.RAW;
                appendRequest.InsertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
                AppendValuesResponse appendValueResponse = appendRequest.Execute();
            }
        }

        private static SheetsService AuthorizeGoogleApp()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.ReadWrite))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-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 Sheets API service.
                var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

                return service;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我能够调整此解决方案,以便在不请求Google增加配额的情况下使流程正常运行。它的运行速度不是很快,但对于~1000条记录来说还可以。

https://github.com/jeffcrowder/GoogleSheetsAPIExample/blob/master/GoogleSheetsAPIExample/Program.cs