以编程方式编辑Google电子表格

时间:2014-05-01 18:57:17

标签: java google-sheets google-spreadsheet-api

我有一个程序可以接收用户输入,但现在我希望每次用户提交表单时都可以通过编辑Google电子表格来保存该输入。基本上,Google电子表格会不断更新。

任何人都可以提供有关我如何实现这一目标的教程吗?我使用Eclipse编写Java,我需要哪些插件?

我已经尝试使用Google Spreadsheets APIadding a list row部分)中提供的一些示例代码,但我似乎无法让它工作。

import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;

import java.io.IOException;
import java.net.*;
import java.util.*;

public class MySpreadsheetIntegration {
  public static void main(String[] args)
      throws AuthenticationException, MalformedURLException, IOException, ServiceException {

    SpreadsheetService service =
        new SpreadsheetService("MySpreadsheetIntegration-v1");

    // TODO: Authorize the service object for a specific user (see other sections)

    // Define the URL to request.  This should never change.
    URL SPREADSHEET_FEED_URL = new URL(
        "https://docs.google.com/spreadsheets/d/1OcDp1IZ4iuvyhndtrZ3OOMHZNSEt7XTaaTrhEkNPnN4/edit#gid=0");

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

    if (spreadsheets.size() == 0) {
      // TODO: There were no spreadsheets, act accordingly.
    }

    // TODO: Choose a spreadsheet more intelligently based on your
    // app's needs.
    SpreadsheetEntry spreadsheet = spreadsheets.get(0);
    System.out.println(spreadsheet.getTitle().getPlainText());

    // Get the first worksheet of the first spreadsheet.
    // TODO: Choose a worksheet more intelligently based on your
    // app's needs.
    WorksheetFeed worksheetFeed = service.getFeed(
        spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
    List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
    WorksheetEntry worksheet = worksheets.get(0);

    // Fetch the list feed of the worksheet.
    URL listFeedUrl = worksheet.getListFeedUrl();
    ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);

    // Create a local representation of the new row.
    ListEntry row = new ListEntry();
    row.getCustomElements().setValueLocal("firstname", "Joe");
    row.getCustomElements().setValueLocal("lastname", "Smith");
    row.getCustomElements().setValueLocal("age", "26");
    row.getCustomElements().setValueLocal("height", "176");

    // Send the new row to the API for insertion.
    row = service.insert(listFeedUrl, row);

  }
}

1 个答案:

答案 0 :(得分:1)

似乎很晚,但肯定会帮助别人!问题在于您的SPREADSHEET_FEED_URL和SpreadSheetService实例的身份验证,因为官方SpreadSheets Api尚未就此进行详细解释。您需要获取身份验证令牌并将其设置在SpreadSheetService Instance上,如下所示:

 private void getAuthenticationToken(Activity activity, String accountName){
            //Scopes used to get access to google docs and spreadsheets present in the drive
            String SCOPE1 = "https://spreadsheets.google.com/feeds";
            String SCOPE2 = "https://docs.google.com/feeds";
            String scope = "oauth2:" + SCOPE1 + " " + SCOPE2;
            String authenticationToken = null;
            try {
                accessToken= GoogleAuthUtil.getToken(activity, accountName, scope);
            }
            catch (UserRecoverableAuthException exception){
    //For first time, user has to give this permission explicitly
                Intent recoveryIntent = exception.getIntent();
                    startActivityForResult(recoveryIntent, RECOVERY_REQUEST_CODE);
            }catch (IOException e) {
                e.printStackTrace();
            } catch (GoogleAuthException e) {
                e.printStackTrace();
            }        
        }

         @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
               if (requestCode == RECOVERY_REQUEST_CODE){
                    if(resultCode == RESULT_OK){
                        if(data != null){
                            String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                            if (accountName != null && !accountName.equals("")){
    //To be called only for the first time after the permission is given
                                getAuthenticationToken(activity, accountName);
                            }
                        }else {
                            Utility.showSnackBar(linearLayout, Constants.INTENT_DATA_NULL);
                        }
                    }
                }
            }

最后在代码下方获取电子邮件帐户中的所有电子表格:

public class MySpreadsheetIntegration {
  public void getSpreadSheetEntries()
      throws AuthenticationException, MalformedURLException, IOException, ServiceException {

    SpreadsheetService service =
        new SpreadsheetService("MySpreadsheetIntegration-v1");
 service = new SpreadsheetService(applicationName);
             service .setProtocolVersion(SpreadsheetService.Versions.V3);
    service .setAuthSubToken(accessToken);

    // Define the URL to request.  This should never change.
    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 = service.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.out.println(spreadsheet.getTitle().getPlainText());
    }
  }
}