Google Sheets API: How to find a row by value and update it's content

后端 未结 2 1056
无人及你
无人及你 2020-12-07 19:04

I am working on an Android application that uses a Google Spreadsheet as a database. The application should GET, APPEND and UPDATE values in a spreadsheet, using the Sheets

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 19:47

    I had the same requirement.

    First: Create a function that gets the index of targeted object from the sheet, like:

    private int getRowIndex(TheObject obj, ValueRange response) {
        List> values = response.getValues();
        int rowIndex = -1;
    
        int i = 0;
        if (values != null) {
            for (List row : values) {
                i += 1;
                if (row.get(1).equals(obj.getBatchId())) {
                    System.out.println("There is a match! i= " + i);
                    rowIndex = i;
                }
            }
        }
    
        return rowIndex;
    }
    

    Second: Create the update method by passing the targeted object having your desired value "batch id" and others new values for the rest of fields.

    public void updateObject(Object obj) throws IOException, GeneralSecurityException {    
        sheetsService = getSheetsService();
        ValueRange response = sheetsService.spreadsheets().
                values().get(SPREADSHEET_ID, "Sheet1").execute();
        
        int rowIndex = this.getRowIndex(obj, response);
        
        if (rowIndex != -1) {
            List oList = new ArrayList<>();
            oList.add(new ValueRange().setRange("B" + rowIndex).setValues(Arrays.asList(
                    Arrays.asList(obj.getSomeProprty()))));
        
            oList.add(new ValueRange().setRange("C" + rowIndex).setValues(Arrays.asList(
                    Arrays.asList(obj.getOtherProprty()))));
        
            //... same for others properties of obj
        
            BatchUpdateValuesRequest body = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(oList);
            BatchUpdateValuesResponse batchResponse;
            batchResponse sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, body).execute();
        } else {
            System.out.println("the obj dont exist in the sheet!");
        }
    }
    
    

    Finally: In your app you have to pass the tageted object to the update method:

    TheObject obj = new Object();
    obj.setBatchId = "some value";
    

    Fill the obj with others values if you want.

    Then call the method:

    objectChanger.updateObject(obj);
    

    提交回复
    热议问题