LoginSignup
2
7

More than 1 year has passed since last update.

C#でスプレッドシートのデータを取得してみた

Posted at

準備

Google Cloudへログイン

スクリーンショット 2022-06-28 5.52.30.png

API登録

「APIとサービスの有効化」をクリックする。
スクリーンショット 2022-06-28 5.58.03.png
「google sheets api」を検索する。
スクリーンショット 2022-06-28 6.02.00.png
「Google Sheets API」をクリックする。
スクリーンショット 2022-06-28 6.03.52.png
APIを有効にする。
スクリーンショット 2022-06-28 6.05.19.png
「OAuth同意画面」をクリックし、「作成」をクリックする。
スクリーンショット 2022-06-28 6.11.43.png
アプリ情報を設定し、保存する。
スクリーンショット 2022-06-28 6.26.30.png
「認証情報を作成」をクリックし、「OAuthクライアントID」をクリックする。
スクリーンショット 2022-06-28 6.38.34.png
赤枠部分をクリックし、OAuthクライアント(JSON)をダウンロードする。
スクリーンショット 2022-06-28 6.50.05.png

ライブラリ追加

Visual StudioでNugetパッケージマネージャを開き、「Google.Apis.Sheets.v4」をインストールする。
スクリーンショット 2022-07-12 7.38.01.png

スプレッドシートからデータを取得する

OAuthクライアント

先程ダウンロードしたOAuthクライアント(JSON)をプロジェクトに追加する。
スクリーンショット 2022-07-12 7.43.25.png

取得するデータ

都道府県が入力されたデータを取得します。
スクリーンショット 2022-07-13 7.11.30.png

サンプルコード

Program.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Util.Store;
using Microsoft.Extensions.Configuration;

namespace SampleGoogleSheetApiConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
            var settings = configuration.GetSection("ApiSettings");
            UserCredential credential;
            using (var stream = new FileStream(
                "client_secret.json",
                FileMode.Open,
                FileAccess.Read))
            {
                string credPath = AppDomain.CurrentDomain.BaseDirectory;
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { SheetsService.Scope.Spreadsheets },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)
                    ).Result;
            }
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = settings["ApplicationName"],
            });
            var request = service.Spreadsheets.Values.Get(settings["SpreadsheetId"], settings["Range"]);
            var values = request.Execute().Values.ToList();
            values.ForEach(value => { Console.WriteLine(value.FirstOrDefault()); });
        }
    }
}
appsettings.json
{
    "ApiSettings": {
        "ApplicationName": "xxxxx",
        "SpreadsheetId": "xxxxx",
        "Range": "Sheet1!A1:A47"
    }
}

実行結果

スクリーンショット 2022-07-13 7.15.39.png

2
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
7