SteveWinward / GoogleSheetsWrapper

Google Sheets API .NET Wrapper Library
MIT License
48 stars 13 forks source link

Weakly typed row insert #15

Closed tymalo closed 2 years ago

tymalo commented 2 years ago

I was looking through the documentation and code and could not see a way to add a row to a sheet without extending the BaseRepository. I just want to append some simple data (row with 3 columns) to a spreadsheet. Is there a way to do this without having to create a class for the data?

SteveWinward commented 2 years ago

@tymalo, I added a few AppendRow methods to the SheetAppender class. This was originally created to make it easy to import CSV files to a Google spreadsheet. But you can now pass lists of strings as row values to append to a sheet. Hopefully this helps. You can also work with the Google Sheet class RowData to make append operations too. Hope this helps!

SteveWinward commented 2 years ago

@tymalo , you'll find the new updates in the nuget package version 1.0.36 that will get released shortly.

SteveWinward commented 2 years ago

@tymalo , I updated the readme file with a sample to add a few rows of string data without creating a strongly typed class. Note that there are a lot of limitations with this. The big one is you can't specify to the Google Sheet API formatting you want applied to the cell. Hope this helps,

// Get the Google Spreadsheet Config Values
var serviceAccount = config["GOOGLE_SERVICE_ACCOUNT"];
var documentId = config["GOOGLE_SPREADSHEET_ID"];
var jsonCredsPath = config["GOOGLE_JSON_CREDS_PATH"];

// In this case the json creds file is stored locally, but you can store this however you want to (Azure Key Vault, HSM, etc)
var jsonCredsContent = File.ReadAllText(jsonCredsPath);

// Create a new SheetHelper class
var sheetHelper = new SheetHelper(documentId, serviceAccount, "");
sheetHelper.Init(jsonCredsContent);

// Append new rows to the spreadsheet
var appender = new SheetAppender(sheetHelper);

// Appends weakly typed rows to the spreadsheeet
appender.AppendRows(new List<List<string>>()
{
    new List<string>(){"7/1/2022", "abc"},
    new List<string>(){"8/1/2022", "def"}
});

// Get all the rows for the first 2 columns in the spreadsheet
var rows = sheetHelper.GetRows(new SheetRange("", 1, 1, 2));

// Print out all the values from the result set
foreach (var row in rows)
{
    foreach (var col in row)
    {
        Console.Write($"{col}\t");
    }

    Console.Write("\n");
}