Программно редактировать таблицу Google

1

У меня есть написанная программа, которая принимает пользовательский ввод, но теперь я хочу сохранить этот ввод, отредактировав таблицу Google каждый раз, когда пользователь отправит форму. Так что, в основном, электронная таблица Google постоянно обновляется.

Может ли кто-нибудь дать учебник о том, как я мог бы это достичь? Я пишу на Java, используя Eclipse, и какие плагины мне нужны?

Я уже пробовал использовать примерный код, представленный в API Google Spreadsheets (добавив раздел строки списка), но я не могу заставить его работать.

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 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 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
    Я по сути скопировал и вставил образец кода Google, но это так. Я просто заменил URL на URL таблицы, которую я хочу отредактировать. Эта таблица может быть доступна и отредактирована кем угодно.
Показать ещё 4 комментария
Теги:
google-spreadsheet
google-spreadsheet-api

1 ответ

0

похоже, очень поздно, но, конечно, это поможет другим! Проблема заключается в вашем SPREADSHEET_FEED_URL и аутентификации экземпляра SpreadSheetService, поскольку официальный SpreadSheets Api не предоставил подробного объяснения относительно этого. Вам нужно получить токен аутентификации и установить его на экземпляр SpreadSheetService, как показано ниже, чтобы заставить его работать:

 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());
    }
  }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню