Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java将数据写入Google电子表格_Java_Google Sheets_Google Drive Api_Google Spreadsheet Api - Fatal编程技术网

使用Java将数据写入Google电子表格

使用Java将数据写入Google电子表格,java,google-sheets,google-drive-api,google-spreadsheet-api,Java,Google Sheets,Google Drive Api,Google Spreadsheet Api,我在这件事上迷路了。我正在尝试将Java与Google电子表格连接起来,尽管API的文档在检索数据方面很完整(并且工作正常),但我无法理解如何写入电子表格 请任何人提供一个完整的例子(包括必要的导入和所有内容),说明如何在Google电子表格中输入非常简单的数据(比如,在Sheet1的A1单元格中输入“asdf”) 如果有这样的教程存在的地方,我找不到它-任何指针将不胜感激 多谢各位, Zsolt使用XmlHttpRequest请求 我会给你一个快速的演示,你可以在谷歌电子表格上写东西。然后,您

我在这件事上迷路了。我正在尝试将Java与Google电子表格连接起来,尽管API的文档在检索数据方面很完整(并且工作正常),但我无法理解如何写入电子表格

请任何人提供一个完整的例子(包括必要的导入和所有内容),说明如何在Google电子表格中输入非常简单的数据(比如,在Sheet1的A1单元格中输入“asdf”)

如果有这样的教程存在的地方,我找不到它-任何指针将不胜感激

多谢各位, Zsolt使用XmlHttpRequest请求

我会给你一个快速的演示,你可以在谷歌电子表格上写东西。然后,您将使用首选语言Java应用这些概念

  • 打开谷歌电子表格进行书写。获取它的电子表格ID
  • 转到并导航到Google Sheets API v4
  • 选择
    https://www.googleapis.com/auth/drive
    权限。单击授权API。允许许可
  • 在步骤2,按“令牌交换授权码”按钮
  • 在步骤3中,根据请求粘贴此URI:

    {电子表格ID}/values/Sheet1!A1?valueInputOption=用户输入

  • HTTP方法是PUT

    将其放在输入请求正文中

    {
      "range":"Sheet1!A1",
      "majorDimension": "ROWS",
      "values": [
        ["Hello World"]
      ],
    }
    
    单击发送请求。如果您得到
    200 OK
    响应,则希望在电子表格的A1单元格中写入“Hello World”。 你可以阅读更多关于


    如何在Java中实现这一点?了解Java中的AJAX或XHR实现。检查以开始。

    好的,我花了好几个小时才最终弄明白,结果证明,答案比从头开始构建Ajax请求更简单。为了给别人节省时间,这里有一个对我有效的解决方案

    Prereqs:我使用,从表中读取,这相当复杂,但对我来说效果很好

    不过,在教程结束后,我需要修改一些内容

    1、换行

    private static final List<String> SCOPES =
            Arrays.asList(SheetsScopes.SPREADSHEETS_READONLY);
    
    但我无法让它工作,因为它需要设置一个
    valueInputOption
    参数,而数小时的搜索也不足以找到可以设置它的位置

    最后,我得到了一个名为

    spreadsheets.values.batchUpdate()
    
    下面是一个代码完整的方法,它为我实现了将
    “Hello World!”
    写入表格单元格的技巧(对于导入,我使用了与上面的Quickstart教程相同的方法):

    void WriteExample()引发IOException{
    Sheets服务=getSheetsService();
    列表请求=新建ArrayList();
    列表值=新的ArrayList();
    添加(新的CellData()
    .setUserEnteredValue(新的扩展值()
    .setStringValue(“你好,世界!”);
    添加(新请求()
    .setUpdateCells(新的UpdateCellsRequest()
    .setStart(新的网格坐标()
    .setSheetId(0)
    .setRowIndex(0)
    .setColumnIndex(0))
    .setRows(Arrays.asList(
    new RowData().setValues(值)))
    .setFields(“userEnteredValue,userEnteredFormat.backgroundColor”);
    BatchUpdateSpreadsheetRequest batchUpdateRequest=新的BatchUpdateSpreadsheetRequest()
    .setRequests(请求);
    service.spreadsheets().batchUpdate(电子表格ID,batchUpdateRequest)
    .execute();
    }
    
    SheetId是您正在编写的工作表的ID(对于特定电子表格中的第一个工作表,它始终为0,对于其他工作表,您可以从URL获取它:它是
    \gid=

    如果您想进一步了解复杂性,如格式化或使用公式,您可以-在本例中,使用

    希望有帮助,
    Zsolt

    这里是快速入门教程代码的修改版本,用于执行写操作

    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.HttpTransport;
    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.ValueRange;
    import java.io.*;
    import java.util.*;
    
    public class SheetsIntegration {
    
        private static HttpTransport transport;
        private static JacksonFactory jsonFactory;
        private static FileDataStoreFactory dataStoreFactory;
    
    我在这行收到了权限警告,但不是致命的

        private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/sheets.googleapis.com.json");
    
    快速入门教程使用只读范围

        private static List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
    
        public SheetsIntegration() {
            try {
                transport = GoogleNetHttpTransport.newTrustedTransport();
                dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
                jsonFactory = JacksonFactory.getDefaultInstance();
    
                service = getSheetsService();
            } catch (Exception e) {
                // handle exception
            }
        }
    
    private static List scopes=Arrays.asList(SheetsScopes.SPREADSHEETS);
    公共页合并(){
    试一试{
    transport=GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory=新文件dataStoreFactory(DATA\u STORE\u DIR);
    jsonFactory=JacksonFactory.getDefaultInstance();
    服务=getSheetsService();
    }捕获(例外e){
    //处理异常
    }
    }
    
    根据快速入门教程,您需要从Google下载认证文件

    public static Credential authorize() throws IOException {
        // Load client secrets.
        File cfile = new File("certs/cert.json");
        cfile.createNewFile();
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream(cfile)));
    
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        transport, jsonFactory, clientSecrets, scopes)
                        .setDataStoreFactory(dataStoreFactory)
                        .setAccessType("offline")
                        .build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        return credential;
    }
    
    public static Sheets getSheetsService() throws IOException {
        Credential credential = authorize();
        return new Sheets.Builder(transport, jsonFactory, credential)
                .setApplicationName("INSERT_YOUR_APPLICATION_NAME")
                .build();
    }
    
    public void writeSomething(List<Data> myData) {
    
        try {
            String id = "INSERT_SHEET_ID";
            String writeRange = "INSERT_SHEET_NAME!A3:E";
    
            List<List<Object>> writeData = new ArrayList<>();
            for (Data someData: myData) {
                List<Object> dataRow = new ArrayList<>();
                dataRow.add(someData.data1);
                dataRow.add(someData.data2);
                dataRow.add(someData.data3);
                dataRow.add(someData.data4);
                dataRow.add(someData.data5);
                writeData.add(dataRow);
            }
    
            ValueRange vr = new ValueRange().setValues(writeData).setMajorDimension("ROWS");
            service.spreadsheets().values()
                    .update(id, writeRange, vr)
                    .setValueInputOption("RAW")
                    .execute();
        } catch (Exception e) {
            // handle exception
        }
    }
    
    public static Credential authorize()引发IOException{
    //加载客户端机密。
    File cfile=新文件(“certs/cert.json”);
    cfile.createNewFile();
    GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(jsonFactory,新的InputStreamReader(新文件InputStream(cfile));
    //生成流并触发用户授权请求。
    GoogleAuthorizationCodeFlow=
    新的GoogleAuthorizationCodeFlow.Builder(
    传输、jsonFactory、客户端机密、范围)
    .setDataStoreFactory(数据存储工厂)
    .setAccessType(“脱机”)
    .build();
    Credential Credential=new AuthorizationCodeInstalledApp(流,new LocalServerReceiver())。授权(“用户”);
    返回凭证;
    }
    公共静态工作表getSheetsService()引发IOException{
    凭证=授权();
    返回新图纸。生成器(运输、jsonFactory、凭证)
    .setApplicationName(“插入您的应用程序名”)
    .build();
    }
    公共无效写入方法(列出myData){
    试一试{
    String id=“插入工作表id”;
    String writeRange=“插入工作表名称!A3:E”;
    List writeData=new ArrayList();
    对于(数据someData:myData){
    List dataRow=new ArrayList();
    
        private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/sheets.googleapis.com.json");
    
        private static List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
    
        public SheetsIntegration() {
            try {
                transport = GoogleNetHttpTransport.newTrustedTransport();
                dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
                jsonFactory = JacksonFactory.getDefaultInstance();
    
                service = getSheetsService();
            } catch (Exception e) {
                // handle exception
            }
        }
    
    public static Credential authorize() throws IOException {
        // Load client secrets.
        File cfile = new File("certs/cert.json");
        cfile.createNewFile();
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream(cfile)));
    
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        transport, jsonFactory, clientSecrets, scopes)
                        .setDataStoreFactory(dataStoreFactory)
                        .setAccessType("offline")
                        .build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        return credential;
    }
    
    public static Sheets getSheetsService() throws IOException {
        Credential credential = authorize();
        return new Sheets.Builder(transport, jsonFactory, credential)
                .setApplicationName("INSERT_YOUR_APPLICATION_NAME")
                .build();
    }
    
    public void writeSomething(List<Data> myData) {
    
        try {
            String id = "INSERT_SHEET_ID";
            String writeRange = "INSERT_SHEET_NAME!A3:E";
    
            List<List<Object>> writeData = new ArrayList<>();
            for (Data someData: myData) {
                List<Object> dataRow = new ArrayList<>();
                dataRow.add(someData.data1);
                dataRow.add(someData.data2);
                dataRow.add(someData.data3);
                dataRow.add(someData.data4);
                dataRow.add(someData.data5);
                writeData.add(dataRow);
            }
    
            ValueRange vr = new ValueRange().setValues(writeData).setMajorDimension("ROWS");
            service.spreadsheets().values()
                    .update(id, writeRange, vr)
                    .setValueInputOption("RAW")
                    .execute();
        } catch (Exception e) {
            // handle exception
        }
    }