Ошибка типа Присвоение столбца переменной ValueRange в Java с помощью API листов Google для добавления? - PullRequest
0 голосов
/ 06 октября 2018

"java.lang.String не может быть преобразован в java.lang.Object"

 public class SheetsQuickstart {
    private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    public ValueRange getValues(String spreadsheetId, String range, Sheets service) throws IOException {

        // [START sheets_get_values]
        ValueRange result = service.spreadsheets().values().get(spreadsheetId, range).execute();
        int numRows = result.getValues() != null ? result.getValues().size() : 0;
        System.out.printf("%d rows retrieved.", numRows);
        // [END sheets_get_values]
        return result;
    }
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    /**
     * Prints the names and majors of students in a sample spreadsheet:
     * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
     */
    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        final String spreadsheetId = "1h6NmjAqRBV-Mg67VYJ6K7nuNKHDzhMB0dP-iTgXuaJM";
        final String range = "A1:E";
        Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();


        ValueRange body = new ValueRange();
        body.setValues(
                Arrays.asList(
                        Arrays.asList("Row 1 Cell 1", "Row 1 Cell 2", "Row 1 Cell 3"),
                        Arrays.asList("Row 2 Cell 1", "Row 2 Cell 2", "Row 2 Cell 3")));

        AppendValuesResponse result =
                service.spreadsheets().values().append(spreadsheetId,"A1", body)
                        .setValueInputOption("RAW")
                        .setInsertDataOption("INSERT_ROWS")
                        .execute();
        System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells());


    }

Я пробовал этот API-интерфейсы Google листов, я новичок в Java.Я не мог понять, как создать valuerange тело.В теле добавления столбцов я получаю сообщение об ошибке типа:

 ValueRange body = new ValueRange().setValues(
                Arrays.asList(
                        Arrays.asList("Row 1 Cell 1", "Row 1 Cell 2", "Row 1 Cell 3"),
                        Arrays.asList("Row 2 Cell 1", "Row 2 Cell 2", "Row 2 Cell 3")));

. Выдает ошибку: (104, 30) java: несовместимые типы: java.util.List > нельзя преобразовать в java.util.List > Я пропустил создание класса?почему выдает эту ошибку.

1 Ответ

0 голосов
/ 07 октября 2018

Изменить String на Object.

ValueRange body = new ValueRange().setValues(
                Arrays.asList(
                        Arrays.asList((Object)"Row 1 Cell 1", (Object)"Row 1 Cell 2",(Object) "Row 1 Cell 3"),
                        Arrays.asList((Object)"Row 2 Cell 1",(Object) "Row 2 Cell 2", (Object)"Row 2 Cell 3")));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...