在Google Sheet中创建一个新工作表c#

时间:2017-01-03 08:27:26

标签: c# .net google-api google-api-dotnet-client google-sheets-api

我可以使用以下代码检索和更新Google表格中的值:

private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (cbYards.Text == "Select Yard")
            {
                MessageBox.Show(@"Please select a yard.");
                return;
            }
            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/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);
            }

            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            IList<IList<Object>> list = new List<IList<Object>>() { };
            for (var i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                var formula = "=IFERROR(VLOOKUP(B"+(i+2)+",Names!$A$2:$B,2,FALSE),\"No Record\")";
                List<object> lists = new List<object>() { formula, dataGridView1.Rows[i].Cells[0].Value.ToString(), 
                    dataGridView1.Rows[i].Cells[1].Value.ToString() };
                list.Add(lists);
            }

            var range = cbYards.Text+"!A2:C";
            ValueRange VRange = new ValueRange();
            VRange.Range = range;
            VRange.Values = list;

            //ValueRange response = request.Execute();
            ValueRange valueRange = new ValueRange();
            valueRange.MajorDimension = "COLUMNS"; 

            SpreadsheetsResource.ValuesResource.UpdateRequest upd = service.Spreadsheets.Values.Update(VRange, spreadsheetId, range);
            upd.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
            UpdateValuesResponse response = upd.Execute();
        }

我的问题是如何在Google工作表中创建我目前正在使用的新工作表。我认为我需要做的就是替换

SpreadsheetsResource.ValuesResource.UpdateRequest upd = service.Spreadsheets.Values.Update(VRange, spreadsheetId, range);

SpreadsheetsResource.ValuesResource.UpdateRequest upd = service.Spreadsheets.create();

但显然这是错误的......

我无法理解如何实施Method: spreadsheets.create

文档中的说明

JSon如何使用C#进行编码?真的很感激帮助。

更新 我在这里找到了这个,但它没有完整,因为它仍然给我一个错误

  

附加信息:未将对象引用设置为对象的实例。

这是更新的代码:

private void button1_Click(object sender, EventArgs e)
        {
            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/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);
            }

            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            string sheetName = string.Format("{0} - {1}-{2}", cbYards.Text, fromDate.Value.ToShortDateString(), toDate.Value.ToShortDateString());
            var myNewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet();
            myNewSheet.Properties = new SpreadsheetProperties();
            myNewSheet.Properties.Title = sheetName;
            var newSheet = service.Spreadsheets.Create(myNewSheet).Execute();
        }

4 个答案:

答案 0 :(得分:6)

客户端库中有一个方法用于创建,您只需要将新的工作表对象传递给它。不要忘记在分配标题之前实例化属性(下面的第2行)

var myNewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet();
myNewSheet.Properties = new SpreadsheetProperties();
myNewSheet.Properties.Title = "Daimtos awsom sheet";
var awsomNewSheet= service.Spreadsheets.Create(myNewSheet).Execute();

注意:我同意您的说明文档页面无用。

答案 1 :(得分:1)

获得空引用的原因是因为您无法拥有没有工作表的电子表格。

var myNewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet();
myNewSheet.Properties = new SpreadsheetProperties();
myNewSheet.Properties.Title = sheetName;

var sheet = new Sheet();
sheet.Properties = new SheetProperties();
sheet.Properties.Title = "Sheet1";
myNewSheet.Properties.Sheets = new List<Sheet>() { sheet };

var newSheet = service.Spreadsheets.Create(myNewSheet).Execute();

答案 2 :(得分:0)

您的更新解决方案非常有效。但是我遇到了“请求认证范围不足”的问题,因为存储的凭据允许只读访问。 我通过删除用户凭据(先前存储在/Users/yourUserName/.credentials/sheets.googleapis.com-projectName/*中)并再次执行应用程序以获取新凭据来解决问题

答案 3 :(得分:0)

下面的代码在我这边工作:

var addSheetRequest = new AddSheetRequest();
addSheetRequest.Properties = new SheetProperties();
addSheetRequest.Properties.Title = sheetName;
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
batchUpdateSpreadsheetRequest.Requests = new List<Request>();
batchUpdateSpreadsheetRequest.Requests.Add(new Request { AddSheet = addSheetRequest });

var batchUpdateRequest = service.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, SpreadsheetId);
batchUpdateRequest.Execute();