如何使用Apps脚本从Google表格中获取数据?

时间:2017-05-30 08:14:37

标签: android google-apps-script

我想创建一个Android应用程序,我使用谷歌Apps脚本进行数据存储(谷歌表)。 现在我想获取那些特定列值相同的行。 在这里,我发送代码,我正在搜索那些职业相同的行。

//Android code

public class FetchData extends AppCompatActivity {

private Button srch;
ArrayAdapter<String> adp1;
Spinner src_gen;
String n, gn;
EditText profession;
private ListView listView;
private ArrayList<MyDataModel> list=new ArrayList < > ();
MyArrayAdapter adapter;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fetch_data);

    srch = (Button) findViewById(R.id.srch);
profession = (EditText) findViewById(R.id.profession);
    src_gen = (Spinner) findViewById(R.id.src_gen);
p= profession.getText.tostring();

    srch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            new FetchDataActivity().execute();
                       }
    });
    adapter = new MyArrayAdapter(ReadSingleData.this, list);
            listView = (ListView) findViewById(R.id.listView);
           listView.setAdapter(adapter);


}



class FetchDataActivity extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int i;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(FetchData.this);
        dialog.setTitle("Please wait...");
        dialog.setMessage("Fetching your values");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        JSONObject jsonObject = fetchData (p);
        try {

            if (jsonObject != null) {

                if (jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray("records");

                    int lenArray = array.length();
                    if (lenArray > 0) {
                        for (; i < lenArray; i++) {

                            MyData data = new MyData ();

                            JSONObject object = array.getJSONObject(jIndex);

                           String name = object.getString("name");
                           String ph = object.getString("phone");

                            data.setName(name);
                            data.setPhone(ph);
                            list.add(data);
                                                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(“VALUE”, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();
        if (list.size() > 0) {
            adapter.notifyDataSetChanged();
        } else {
            Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_LONG).show()
    }
    }
}

Private JSONObject fetchData (String prof){
public static final String URL = ” 
 https://script.google.com/macros/s/XXXXXXXXXXXXXX/exec?”;  
try {
public static final String URL = 
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL+"action=read&profession="+ prof)
            .build();
    response = client.newCall(request).execute();
     Log.e(TAG,"response"+response.body().string());
    return new JSONObject(response.body().string());

} catch (@NonNull IOException | JSONException e) {
    Log.e(TAG, "fetching null " + e.getLocalizedMessage());
}
return null;
}

//***************AppsScript code

function doGet(e) {
var op = e.parameter.action;

var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/XXXXXXXX/edit?usp=sharing");
var sheet = ss.getSheetByName("Sheet1");

if (op == "read")
    return fetch_value(e, sheet);

}
function fetch_value (request, sheet){
 var output = ContentService.createTextOutput(),
  data = {};
   var sheet = "sheet1"
var profession = request.parameter. profession;
var rows=[];
var tdata=[];    
var flag = 1,r=0;
var sh = ss.getSheetByName(sheet);

if (typeof properties == "undefined") {
    properties = getHeaderRow_(ss, sheet);
    properties = properties.map(function(p) {
        return p.replace(/\s+/g, '_');
    });
}
    var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
    var prof = sheet.getRange(i, 2).getValue();
    if (prof == profession) {
        flag = 0;
        rows[r++]= sh.getRange(i, 2, 1, sh.getLastColumn()).getValues();
        var row=rows[r],record={};
           for (var p in properties) {
            record[properties[p]] = row[p];
          }

    tdata.push(record);
  }
    }    
    data.records = tdata;}
        if (flag == 1){
     data = " no data found";
    }
var callback = request.parameters.callback;
if (callback === undefined) {
    output.setContent(JSON.stringify(data));
} else {
    output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;}

function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);

return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}

1 个答案:

答案 0 :(得分:0)

使用以下内容更改功能代码。

var prof = sheet.getDataRange().getValue();
for (var i = 1; i <= prof.length; i++) {
    if (prof[i][2] == profession) { // If your professor name in first column use 0
       tdata.push(prof[i][0]);      
    }
}