如何在ASP.NET MVC中使用API​​ v4创建新的Google表格

时间:2018-06-30 09:47:08

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

基于:https://www.twilio.com/blog/2017/03/google-spreadsheets-and-net-core.html

我创建了一个新文件client_secret.json,然后在ASP.NET MVC上创建了一个新的Google表格,它运行成功,未返回任何错误,但未创建Google表格。这是我的代码

public class GoogleSheet
{
    static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets, SheetsService.Scope.Drive};
    static readonly string ApplicationName = "Current Legislators";

    private SheetsService CreateService()
    {
        GoogleCredential credential;
        using (var stream = new FileStream(HostingEnvironment.MapPath("/client_secret.json"), FileMode.Open, FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(Scopes);
        }

        // Create Google Sheets API service.
        var service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        return service;
    }

    private string CreateNewSheet(SheetsService service, string fileName, string sheetName)
    {
        var newSheet = new Spreadsheet();
        newSheet.Properties = new SpreadsheetProperties() { Title = fileName };
        Sheet sheet = new Sheet();
        sheet.Properties = new SheetProperties() { Title = sheetName };
        newSheet.Sheets = new List<Sheet>();
        newSheet.Sheets.Add(sheet);
        var result = service.Spreadsheets.Create(newSheet).Execute();
        return result.SpreadsheetId;
    }

    public string InsertData(string fileName, string sheetName, int column = 1)
    {
        try
        {
            var range = $"{sheetName}!A1:F";
            var valueRange = new ValueRange();
            var service = CreateService();
            var row1 = new List<object>() { "Hello 1!", "This 1", "was 1", "insertd 1", "via 1", "C#" };
            var row2 = new List<object>() { "Hello 2!", "This 2", "was 2", "insertd 2", "via 2", "C" };
            var row3 = new List<object>() { "Hello 3!", "This 3", "was 3", "insertd 3", "via 3", "C++" };
            valueRange.Values = new List<IList<object>> { row1, row2, row3 };
            var spreadsheetId = CreateNewSheet(service, fileName, sheetName);
            var appendRequest = service.Spreadsheets.Values.Append(valueRange, spreadsheetId, range);
            appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
            appendRequest.InsertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
            var appendReponse = appendRequest.Execute();
            return appendReponse.SpreadsheetId;
        }
        catch (Exception ex)
        {
            return string.Empty;
        }
    }
}

能帮我解决这个问题吗?

0 个答案:

没有答案