如何将 Android 应用程序与 Google Sheets 电子表格连接起来?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12478582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:47:01  来源:igfitidea点击:

How do I connect Android apps with Google Sheets spreadsheets?

androidgoogle-sheetsgoogle-apigoogle-docs-apigoogle-sheets-api

提问by user1680435

I'm trying to do an Android app that needs to work with Google spreadsheet API. I'm new in this, so I'm starting with the version 3 of the api: https://developers.google.com/google-apps/spreadsheets/

我正在尝试制作一个需要使用 Google 电子表格 API 的 Android 应用程序。我是新手,所以我从 api 的第 3 版开始:https: //developers.google.com/google-apps/spreadsheets/

I followed all the steps, downloaded all the jar files to libsubfolder in my project folder and then I added to the build path in Eclipse as usual. So although there is no Java example to perform Oauth 2.0, I just tried to declare:

我按照所有步骤,将所有 jar 文件下载到lib我的项目文件夹中的子文件夹,然后像往常一样添加到 Eclipse 中的构建路径。因此,虽然没有执行 Oauth 2.0 的 Java 示例,但我只是尝试声明:

SpreadsheetService service = new SpreadsheetService("v1");

but when I emulate this simple line it gives me an error:

但是当我模拟这条简单的线时,它给了我一个错误:

java.lang.NoClassDefFoundError: com.google.gdata.client.spreadsheet.SpreadsheetService

I'm using all the jars included in the documentation and I have the import:

我正在使用文档中包含的所有 jars 并且我有导入:

import com.google.gdata.client.spreadsheet.SpreadsheetService;

but I am totally lost. I dont know what else to do just to start, connect to Google APIs and work with the spreadsheets.

但我完全迷失了。我不知道还能做些什么来开始、连接到 Google API 并使用电子表格。

采纳答案by user1680435

Thank you so so much Scorpion! It works!! I've been trying this for too long. Ok here is my solution: I started a new project and included these jars:

非常感谢蝎子!有用!!我已经尝试这个太久了。好的,这是我的解决方案:我开始了一个新项目并包含了这些 jars:

gdata-client-1.0
gdata-client-meta-1.0
gdata-core-1.0
gdata-spreadsheet-3.0
gdata-spreadsheet-meta-3.0
guava-13.0.1  

and my code:

和我的代码:

    SpreadsheetService spreadsheet= new SpreadsheetService("v1");
    spreadsheet.setProtocolVersion(SpreadsheetService.Versions.V3);

    try {
        spreadsheet.setUserCredentials("username", "password");
        URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
        SpreadsheetFeed feed = spreadsheet.getFeed(metafeedUrl, SpreadsheetFeed.class);

        List<SpreadsheetEntry> spreadsheets = feed.getEntries();
        for (SpreadsheetEntry service : spreadsheets) {             
            System.out.println(service.getTitle().getPlainText());
       }
    } catch (AuthenticationException e) {           
        e.printStackTrace();
    }

of course this is executed in a different thread not in the main thread. There is no java documentation for OAuth 2.0 but I will try and if I can't do it I'll ask here. Again, thank you very much and I hope to help you when I work on this time enough. :)

当然,这是在不同的线程中执行的,而不是在主线程中。没有 OAuth 2.0 的 Java 文档,但我会尝试,如果我做不到,我会在这里问。再次,非常感谢你,我希望在我这次工作足够的时候帮助你。:)

回答by Scorpion

Sample code for you without OAuth 2.0. But its recommended to perform OAuth as its good for the security purpose. You also have to add below permissions.

没有 OAuth 2.0 的示例代码。但为了安全起见,建议执行 OAuth。您还必须添加以下权限。

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Sample Code:-

示例代码:-

try {
    SpreadsheetEntry spreadsheet;
    service = new SpreadsheetService("Spreadsheet");
    service.setProtocolVersion(SpreadsheetService.Versions.V3);
    service.setUserCredentials("username", "password");//permission required to add in Manifest
    URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
    feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);

    List<SpreadsheetEntry> spreadsheets = feed.getEntries();
    if (spreadsheets.size() > 0) {
        spreadsheet = spreadsheets.get(i);//Get your Spreadsheet
   }
} catch (Exception e) {
    e.printStackTrace();
}

回答by Nels Beckman

It's a complex process, but it can be done! I wrote a blog poston getting the basics up and running. And I've also published an open-source projectthat is actually useful, but still quite minimal. It uses OAuth, and therefore can pull the permission directly from Android's permission model (no hardcoded email/password!).

这是一个复杂的过程,但它可以做到!我写了一篇关于启动和运行基础知识的博客文章。而且我还发布了一个开源项目,它实际上很有用,但仍然很少。它使用 OAuth,因此可以直接从 Android 的权限模型中获取权限(没有硬编码的电子邮件/密码!)。

You need something to start the "Choose account intent":

您需要一些东西来启动“选择帐户意图”:

    View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
         Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
                 false, null, null, null, null);
         startActivityForResult(intent, 1);

        if (AUTO_HIDE) {
            delayedHide(AUTO_HIDE_DELAY_MILLIS);
        }
        return false;
    }
};

And then when that intent returns, you can try to use the token that was returned (although note, if it's the first time the user may have to explicitly authorize your program; that's the UserRecoverableAuthException):

然后当该意图返回时,您可以尝试使用返回的令牌(但请注意,如果这是用户第一次必须明确授权您的程序;那就是 UserRecoverableAuthException):

    protected void onActivityResult(final int requestCode, final int resultCode,
        final Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {
        final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        System.err.println(accountName);

        (new AsyncTask<String, String,String>(){
            @Override
            protected String doInBackground(String... arg0) {
                try {
                    // Turn account name into a token, which must
                    // be done in a background task, as it contacts
                    // the network.
                    String token = 
                            GoogleAuthUtil.getToken(
                                    FullscreenActivity.this, 
                                    accountName, 
                                    "oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds");
                    System.err.println("Token: " + token);

                    // Now that we have the token, can we actually list
                    // the spreadsheets or anything...
                    SpreadsheetService s =
                            new SpreadsheetService("Megabudget");
                    s.setAuthSubToken(token);

                    // Define the URL to request.  This should never change.
                    // (Magic URL good for all users.)
                    URL SPREADSHEET_FEED_URL = new URL(
                        "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

                    // Make a request to the API and get all spreadsheets.
                    SpreadsheetFeed feed;
                    try {
                        feed = s.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
                        List<SpreadsheetEntry> spreadsheets = feed.getEntries();

                        // Iterate through all of the spreadsheets returned
                        for (SpreadsheetEntry spreadsheet : spreadsheets) {
                          // Print the title of this spreadsheet to the screen
                          System.err.println(spreadsheet.getTitle().getPlainText());
                        }
                    } catch (ServiceException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (UserRecoverableAuthException e) {
                    // This is NECESSARY so the user can say, "yeah I want
                    // this app to have permission to read my spreadsheet."
                    Intent recoveryIntent = e.getIntent();
                    startActivityForResult(recoveryIntent, 2);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (GoogleAuthException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }}).execute();
  } else if (requestCode == 2 && resultCode == RESULT_OK) {
      // After the user YAYs or NAYs our permission request, we are
      // taken here, so if we wanted to grab the token now we could.
  }

}

回答by wescpy

(Feb 2017)The question (and most answers) are now out-of-date as:

(2017 年 2 月)这个问题(和大多数答案)现在已经过时了:

  1. GData APIsare the previous generation of Google APIs. While not all GData APIs have been deprecated, all modernGoogle APIsdo notuse the Google Data protocol
  2. Google released a new Google Sheets API(v4; not GData) in 2016, and
  3. Android Studiois now the preferred IDE over Eclipse. In order to use Google APIs, you need to get the Google APIs Client Library for Android(or for more general Java, the Google APIs Client Library for Java). Now you're set.
  1. GData API是上一代 Google API。虽然不是所有的GData API与已被否决,所有现代谷歌的API没有使用谷歌数据协议
  2. Google在 2016 年发布了新的 Google Sheets API(v4;不是 GData),并且
  3. Android Studio现在是优于 Eclipse 的首选 IDE。为了使用 Google API,您需要获取适用于 Android 的 Google API 客户端库(或者对于更通用的 Java,需要获取适用于 Java的 Google API 客户端库)。现在你准备好了。

To start, the latest Sheets APIis much more powerful than all older versions. The latest API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resize rows/columns, add pivot tables, create charts, etc.).

首先,最新的Sheets API比所有旧版本都强大得多。最新的 API 提供了旧版本中不可用的功能,即让开发人员以编程方式访问工作表,就像您在使用用户界面一样(创建冻结行、执行单元格格式设置、调整行/列大小、添加数据透视表、创建图表等。 )。

That said, yeah, it's tough when there aren't enough good (working) examples floating around, right? In the official docs, we try to put "quickstart" examples in as many languages as possible to help get you going. In that spirit, here are the Android quickstart code sampleas well as the more general Java Quickstart code sample. For convenience, here's the Sheets API JavaDocs reference.

也就是说,是的,当没有足够的好(工作)示例漂浮时,这很困难,对吧?在官方文档中,我们尝试以尽可能多的语言提供“快速入门”示例,以帮助您入门。本着这种精神,这里有Android 快速入门代码示例以及更通用的Java 快速入门代码示例。为方便起见,这里是Sheets API JavaDocs 参考

Another answer suggested using OAuth2 for data authorization, which you can do with this auth snippet from the quickstart above, plus the right scope:

另一个答案建议使用 OAuth2 进行数据授权,您可以使用上面快速入门中的这个 auth 片段,加上正确的范围

// Sheets RO scope
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS_READONLY};
    :

// Initialize credentials and service object
mCredential = GoogleAccountCredential.usingOAuth2(
        getApplicationContext(), Arrays.asList(SCOPES))
        .setBackOff(new ExponentialBackOff());

If you're not "allergic" to Python, I've made several videos with more "real-world" examples using the Sheets API (non-mobile though):

如果您对 Python 不“过敏”,我已经使用 Sheets API 制作了几个带有更多“真实世界”示例的视频(非移动设备):

Finally, note that the Sheets API performs document-orientedfunctionality as described above. For file-levelaccess, i.e. import, export etc. you'd use the Google Drive APIinstead; specifically for mobile, use the Google Drive Android API. Hope this helps!

最后,请注意 Sheets API 执行如上所述的面向文档的功能。对于文件级访问,即导入、导出等,您可以改用Google Drive API;专门针对移动设备,请使用Google Drive Android API。希望这可以帮助!