如何使用Sheets APIv4 Java在Google表格中插入一行

时间:2019-02-12 18:11:02

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

如果我想使用Java在指定的索引处向Google工作表中插入一行,然后写入该行,我将如何处理?

2 个答案:

答案 0 :(得分:2)

我不能对 Elric 的回答发表评论,但我想纠正一下。

要添加带有您的值的单行,请在方法中:

requestBuilder \

它应该是 .setMajorDimension("COLUMNS") 而不是 "ROWS

我希望这会有所帮助。

答案 1 :(得分:0)

经过大量的谷歌搜索,一些努力和调整后的答案,我得以弄清楚这一点:https://stackoverflow.com/a/48286666/1146032

注意:您可以在此处生成凭据。https://developers.google.com/sheets/api/quickstart/java在大多数IDE中都位于“ resources”文件夹中

这是我完整使用的代码-您需要的相关方法是下面的 insertRow 方法,该方法是从 writeTest 调用的。只会发布有问题的方法,但是在sheets API中肯定缺少“ quickstart”,因此这里是完整的源代码:

类别和导入

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SheetsTest {
    private static final String APPLICATION_NAME = "Metrics project";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
    private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

getCredentials

private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException{
    InputStream in = SheetsTest.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}

writeTest

//Creates a new row at row 2 then writes data to it...
static void writeTest(Report r, String sheetID, String range)throws GeneralSecurityException, IOException{
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    ValueRange requestBody = requestBuilder(r, range);
    Sheets sheetsService = new Sheets.Builder(HTTP_TRANSPORT,JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();
    insertRow(sheetsService, sheetID);
    Sheets.Spreadsheets.Values.Append request =
            sheetsService.spreadsheets().values().append(sheetID, range, requestBody);
    request.setValueInputOption("RAW");
    //request.setInsertDataOption("INSERT_ROWS");
    AppendValuesResponse resp = request.execute();

    System.out.println(resp);
}

insertRow

//Inserts row at index, this is hardcoded to row 2 (0-indexed)
private static void insertRow(Sheets ss, String sheetID)throws IOException{
    InsertDimensionRequest insertRow = new InsertDimensionRequest();
    insertRow.setRange(new DimensionRange().setDimension("ROWS").setStartIndex(1).setEndIndex(2).setSheetId(0));

    BatchUpdateSpreadsheetRequest r = new BatchUpdateSpreadsheetRequest().setRequests(Arrays.asList(
            new Request().setInsertDimension(insertRow)
    ));
    ss.spreadsheets().batchUpdate(sheetID, r).execute();
}

requestBuilder

//Populate ValueRange
static ValueRange requestBuilder( Report r, String range){
    ValueRange v = new ValueRange()
        .setValues(Arrays.asList(
            Arrays.asList(r.value1),
            Arrays.asList(r.value2),
            Arrays.asList(r.value3),
            Arrays.asList(r.value4),
            Arrays.asList(r.value5)
        ))
        .setMajorDimension("ROWS")
        .setRange(range)
    ;
    return v;
}