How to add a sheet in google sheets API v4 in C#?

前端 未结 5 1709
無奈伤痛
無奈伤痛 2021-02-10 21:28

I\'ve been using Google Sheets API, and following The Google Guide. However there is no example, even beyond the second page of google, to add a worksheet and write to a new she

5条回答
  •  梦如初夏
    2021-02-10 21:57

    I have the code to add a sheet as well, but it seems like you figured it out. Here is some code to add content to the sheet. It differs from what others have posted by a little bit, but it should help whoever sees this post.

    In this code, it would insert the values of colNames into the row starting at (0,0). So if sheet uses this notation (row, col), then
    (0,0)=timestamp
    (0,1)=videoid
    (0,2)=videoname
    (0,3)=firstname
    (0,4)=lastname
    (0,5)=email

    So the whole first row would be filled with the colNames values

            var reqs = new BatchUpdateSpreadsheetRequest();
            reqs.Requests = new List();
            string[] colNames = new [] { "timestamp", "videoid", "videoname", "firstname", "lastname", "email" };
    
            // Create starting coordinate where data would be written to
    
            GridCoordinate gc = new GridCoordinate();
            gc.ColumnIndex = 0;
            gc.RowIndex = 0;
            gc.SheetId = SHEETID; // Your specific sheet ID here
    
            rq = new Request();
            rq.UpdateCells = new UpdateCellsRequest();
            rq.UpdateCells.Start = gc;
            rq.UpdateCells.Fields = "*"; // needed by API, throws error if null
    
            // Assigning data to cells
            RowData rd = new RowData();
            List lcd = new List();
            foreach (String column in colNames)
            {
                ExtendedValue ev = new ExtendedValue();
                ev.StringValue = column;
    
                CellData cd = new CellData();
                cd.UserEnteredValue = ev;
                lcd.Add(cd);
            }
            rd.Values = lcd;
    
            // Put cell data into a row
            List lrd = new List();
            lrd.Add(rd);
            rq.UpdateCells.Rows = lrd;
    
            // It's a batch request so you can create more than one request and send them all in one batch. Just use reqs.Requests.Add() to add additional requests for the same spreadsheet
            reqs.Requests.Add(rq);
    
            // Execute request
            response = sheetsService.Spreadsheets.BatchUpdate(reqs, Spreadsheet.SpreadsheetId).Execute(); // Replace Spreadsheet.SpreadsheetId with your recently created spreadsheet ID
    

提交回复
热议问题