GData APIでGoogleスプレッドシートを参照するにはSpreadsheets Data APIを使うための基礎知識(1)(2/3 ページ)

» 2010年01月15日 00時00分 公開
[能登諭株式会社トップゲート]

Googleスプレッドシート参照プログラムの作成

Spreadsheets Data API用のJavaプロジェクトの作成

 では、Eclipse上にGData APIを操作するためのプロジェクトを作っていきましょう。以下の4手順を実施してください。

  1. 「gdata-api」という名前のJavaプロジェクトを作成
  2. 先ほど解凍した「gdata/java/lib」フォルダを「gdata-api」プロジェクト直下にコピー
  3. 「gdata/java/deps」フォルダ内のjarファイルを「gdata-api」プロジェクトの「lib」フォルダにコピー
  4. 「lib」フォルダ内の以下のjarファイルをクラスパスに追加
  • gdata-core-1.0.jar
  • gdata-client-meta-1.0.jar
  • gdata-client-1.0.jar
  • gdata-spreadsheet-meta-3.0.jar
  • gdata-spreadsheet-3.0.jar
  • google-collect-1.0-rc1.jar
  • jsr305.jar

 以上の作業を終えると、以下のようになっているはずです。

図3 Spreadsheets Data API用のJavaプロジェクトの構成 図3 Spreadsheets Data API用のJavaプロジェクトの構成

検索プログラムのコーディング

 では、実際にプログラムからSpreadsheets Data APIを利用して、スプレッドシートを検索してみましょう。sampleパッケージを作成し、その中に「SpreadsheetSearch」というJavaファイルを作成して、以下の内容をコピーしてください。

package sample;
   
import java.io.IOException;
   
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.ListQuery;
import com.google.gdata.client.spreadsheet.SpreadsheetQuery;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CustomElementCollection;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.ServiceException;
   
public class SpreadsheetSearch {
    public static void main(String[] args) throws IOException, ServiceException {
        // このアプリケーションの名称。任意の名前を設定
        String applicationName = "topgate.co.jp-SpreadsheetSearch-1";
        // Google AppsもしくはGoogleアカウントのメールアドレスとパスワードを設定
        String username = "";
        String password = "";
        // Spreadsheetsサービスへの認証を行う
        SpreadsheetService service = new SpreadsheetService(applicationName);
        service.setUserCredentials(username, password);
   
        // 検索対象のスプレッドシートを取得
        FeedURLFactory urlFactory = FeedURLFactory.getDefault();
        SpreadsheetQuery spreadsheetQuery = new SpreadsheetQuery(urlFactory
                .getSpreadsheetsFeedUrl());
        spreadsheetQuery.setTitleQuery("検索データ"); // 検索対象のスプレッドシート名を指定している
        SpreadsheetFeed spreadsheetFeed = service.query(spreadsheetQuery,
                SpreadsheetFeed.class);
        SpreadsheetEntry spreadsheetEntry = spreadsheetFeed.getEntries().get(0);
        System.out.println("名前:" + spreadsheetEntry.getTitle().getPlainText());
   
        // 検索対象のワークシートを取得
        WorksheetEntry worksheetEntry = spreadsheetEntry.getDefaultWorksheet();
    
        // ワークシート内を検索
        ListQuery listQuery = new ListQuery(worksheetEntry.getListFeedUrl());
        listQuery.setSpreadsheetQuery("名称 = りんご");
        ListFeed listFeed = service.query(listQuery, ListFeed.class);
        ListEntry listEntry = listFeed.getEntries().get(0);
        CustomElementCollection elements = listEntry.getCustomElements();
        System.out.println("名称:" + elements.getValue("名称"));
        System.out.println("数量:" + elements.getValue("数量"));
        System.out.println("価格:" + elements.getValue("価格"));
    }
}
SpreadsheetSearch.java

 次に、usernameとpassword変数に自分のメールアドレスとパスワードを設定してください。設定後に実行すると、以下の結果が表示されるはずです。

図4 実行結果 図4 実行結果

Spreadsheets Data APIを使うためのコードの詳細

Spreadsheetsサービスのインスタンス生成

        // このアプリケーションの名称。任意の名前を設定
        String applicationName = "topgate.co.jp-SpreadsheetSearch-1";
        // Google AppsもしくはGoogleアカウントのメールアドレスとパスワードを設定
        String username = "";
        String password = "";
        // Spreadsheetsサービスへの認証を行う
        SpreadsheetService service = new SpreadsheetService(applicationName);
        service.setUserCredentials(username, password);

 Spreadsheetsサービスを利用するには、SpreadsheetServiceクラスのインスタンスを生成し、認証を行う必要があります。SpreadsheetServiceのコンストラクタは何種類か存在しますが、必ずアプリケーション名を指定する必要があります。アプリケーション名はJavadocで、「[company-id]-[app-name]-[app-version]というフォーマットにすべき」と記述されています。

Spreadsheetsサービスへの認証

 次に、認証を行います。認証は、setUserCredentialsメソッドで行います。usernameには、Google AppsもしくはGoogleアカウントのメールアドレスを設定してください。認証に失敗した場合、InvalidCredentialsExceptionがthrowされます。throwされた場合は、設定したメールアドレスとパスワードを見直してください。

Exception in thread "main" com.google.gdata.client.GoogleService$InvalidCredentialsException: Invalid credentials
    at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:586)
    at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:490)
    at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:336)
    at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:362)
    at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:317)
    at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:301)
    at sample.SpreadsheetSearch.main(SpreadsheetSearch.java:26)

 次ページでは、引き続きコードを詳細に解説し、最後にスプレッドシートを検索/参照する際の3つのポイントをお話します。

コラム 「GData APIで使える3つの認証方式」

なお今回行った認証方式は、「ClientLogin」という認証方式です。ClientLoginは単一のユーザーが利用するアプリケーションを前提とした認証方式です。

GData APIには、ほかにも複数のユーザーが利用するWebアプリケーション用の認証方式が存在します。Webアプリケーション用の認証方式では「AuthSub」「OAuth」の2つの認証方式が存在します。どちらもWebアプリケーション側でユーザーのメールアドレスとパスワードを管理する必要がありません。

詳細は、「Authenticating to the Spreadsheets service」「Authentication in the Google Data Protocol」を参照してください。


Copyright © ITmedia, Inc. All Rights Reserved.

RSSについて

アイティメディアIDについて

メールマガジン登録

@ITのメールマガジンは、 もちろん、すべて無料です。ぜひメールマガジンをご購読ください。