【问题标题】:Kotlin read and display data from Google SheetsKotlin 从 Google 表格中读取和显示数据
【发布时间】:2022-02-04 18:59:57
【问题描述】:

有人可以帮我完成我想做的事情吗?我花了几个小时看视频和上网谷歌自己做。但是,我不能,因为我无法找到从 Google 表格中仅读取一个单元格值的帮助,而且我也找不到 Kotlin 的代码。

我想要的只是在 MainActivity 的文本视图中的 Google 表格中的单元格 B2 中显示值。

我是 Android 应用开发新手。

提前致谢。

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    我建议制作 google sheet public,然后您可以以 csv 或其他格式访问它,但 csv 是最简单的。您可以根据工作表 id 构造 url:

    val url = "https://docs.google.com/spreadsheets/d/e/${id}/pub?output=csv"
    

    例如,您可以使用ktor 获取内容:

    suspend fun getUrlAsString(url: String): String {
        val client = HttpClient(Android) {
        }
        return client.get<String>(url)
    }
    

    如何解析 csv 的示例,但您可以使用一些库或自己解析文本,这很简单:

    fun parseCsv(text: String): List<Map<String, String>> {
        val reader = CSVReaderBuilder(StringReader(text))
                .build()
        val lines = reader.readAll()
        val firstLine = lines.removeAt(0)
    
        val result = lines.map { line ->
            firstLine.mapIndexed { index, label ->
                label to line[index]
            }.toMap()
        }
        if (result.size > 4)
            println(result[4])
        return result
    
    }
    

    【讨论】:

      【解决方案2】:

      我有代码可以从谷歌表格中获取价值,让我分享给你。

      首先,您需要创建一个电子表格,并且您需要创建 api 密钥才能访问电子表格 api。

      我的电子表格数据

      --> 当您在文件选项中创建电子表格时-> 发布到网络。它会生成一个链接。 -> 从该链接获取工作表 ID。它会像

      https://docs.google.com/spreadsheets/d/your-id-//edit#gid=0

      --> 在给定的 url 上,您必须输入您的工作表 ID 工作表名称和您从 google console 生成的 api 密钥

      您可以从生成的 url 获取数据的 json 格式到电子表格中。 您的网址将如下所示。

      https://sheets.googleapis.com/v4/spreadsheets/YOUR_SHEET_ID/values/YOUR_SHEET_NAME?alt=json&key=YOUR_API_KEY

      在浏览器中打开这个 url 并从电子表格中获取数据的 json 格式。

      获取数据后

      这是从电子表格中检索数据的代码。

      首先你需要一个模型类来从 json 中获取数据。

      class model {
              // variables for our first name,
              // last name, email and avatar
              private var first_name: String? = null
              private var last_name: String? = null
              private var email: String? = null
      
              constructor(first_name: String, last_name: String, email: String){
                  this.first_name = first_name;
                  this.last_name = last_name;
                  this.email = email;
              }
      
              fun getFirst_name(): String? {
                  return first_name
              }
      
              fun setFirst_name(first_name: String?) {
                  this.first_name = first_name
              }
      
              fun getLast_name(): String? {
                  return last_name
              }
      
              fun setLast_name(last_name: String?) {
                  this.last_name = last_name
              }
      
              fun getEmail(): String? {
                  return email
              }
      
              fun setEmail(email: String?) {
                  this.email = email
              }
      
      }
      

      BaseModel.kt

      class BaseModel {
          @SerializedName("range")
          @Expose
          private var range: String? = null
      
          @SerializedName("majorDimension")
          @Expose
          private var majorDimension: String? = null
      
          @SerializedName("values")
          @Expose
          private var values: List<List<model?>?>? = null
      
          fun getRange(): String? {
              return range
          }
      
          fun setRange(range: String?) {
              this.range = range
          }
      
          fun getMajorDimension(): String? {
              return majorDimension
          }
      
          fun setMajorDimension(majorDimension: String?) {
              this.majorDimension = majorDimension
          }
      
          fun getValues(): List<List<model?>?>? {
              return values
          }
      
          fun setValues(values: List<List<model?>?>?) {
              this.values = values
          }
      
      }
      

      activity_main.xml

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context=".MainActivity">
      
          <androidx.recyclerview.widget.RecyclerView
              android:id="@+id/idRVUsers"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:listitem="@layout/user_rv_item" />
      
          <!--we are adding progress bar for thepurpose of loading-->
          <ProgressBar
              android:id="@+id/idPBLoading"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerInParent="true"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      user_rv_item.xml

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.cardview.widget.CardView
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:elevation="8dp"
          app:cardCornerRadius="8dp">
      
          <RelativeLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_margin="2dp">
      
              <!--image view for displaying user image-->
              <ImageView
                  android:id="@+id/idIVUser"
                  android:layout_width="100dp"
                  android:src="@drawable/ic_launcher_foreground"
                  android:layout_height="100dp"
                  android:layout_margin="10dp" />
      
              <!--text view for displaying first name-->
              <TextView
                  android:id="@+id/idTVFirstName"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_marginTop="10dp"
                  android:layout_toEndOf="@id/idIVUser"
                  android:layout_toRightOf="@id/idIVUser"
                  android:text="First Name"
                  android:textColor="@color/black"
                  android:textSize="15sp" />
      
              <!--text view for displaying last name-->
              <TextView
                  android:id="@+id/idTVLastName"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_below="@id/idTVFirstName"
                  android:layout_marginTop="10dp"
                  android:layout_toEndOf="@id/idIVUser"
                  android:layout_toRightOf="@id/idIVUser"
                  android:text="Last Name"
                  android:textColor="@color/black"
                  android:textSize="15sp" />
      
              <!--text view for displaying user email-->
              <TextView
                  android:id="@+id/idTVEmail"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_below="@id/idTVLastName"
                  android:layout_marginTop="10dp"
                  android:layout_toEndOf="@id/idIVUser"
                  android:layout_toRightOf="@id/idIVUser"
                  android:text="Email"
                  android:textColor="@color/black"
                  android:textSize="15sp" />
      
          </RelativeLayout>
      
      </androidx.cardview.widget.CardView>
      

      rv_adapter.kt

      import android.content.Context
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import android.widget.TextView
      import androidx.recyclerview.widget.RecyclerView
      
      class UserRVAdapter(modelArraylist: ArrayList<model>) :
          RecyclerView.Adapter<UserRVAdapter.ViewHolder>() {
      
          // variable for our array list and context.
          private val userModalArrayList: ArrayList<model> = modelArraylist
          private val context: Context? = null
      
          class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
              val firstNameTV: TextView? = itemView.findViewById(R.id.idTVFirstName)
              var lastNameTV: TextView? = itemView.findViewById(R.id.idTVLastName)
              var emailTV: TextView? = itemView.findViewById(R.id.idTVEmail)
      
          }
      
          override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
              val view: View =
                  LayoutInflater.from(parent.context).inflate(R.layout.user_rv_item, parent, false)
              return ViewHolder(view)
          }
      
          override fun onBindViewHolder(holder: ViewHolder, position: Int) {
              // getting data from our array list in our modal class.
              // getting data from our array list in our modal class.
              val userModal: model = userModalArrayList[position]
      
              // on the below line we are setting data to our text view.
      
              // on the below line we are setting data to our text view.
              holder.firstNameTV?.setText(userModal.getFirst_name())
              holder.lastNameTV?.setText(userModal.getLast_name())
              holder.emailTV?.setText(userModal.getEmail())
          }
      
          override fun getItemCount(): Int {
              return userModalArrayList.size
          }
      }
      

      MainActivity.kt

       import android.os.Bundle
          import android.view.View
          import android.widget.ProgressBar
          import android.widget.Toast
          import androidx.appcompat.app.AppCompatActivity
          import androidx.recyclerview.widget.LinearLayoutManager
          import androidx.recyclerview.widget.RecyclerView
          import com.android.volley.Request
          import com.android.volley.Response
          import com.android.volley.VolleyError
          import com.android.volley.toolbox.JsonObjectRequest
          import com.android.volley.toolbox.Volley
          import org.json.JSONException
          import org.json.JSONObject
          
          
          class MainActivity : AppCompatActivity() {
          
              private var userModalArrayList: ArrayList<model>? = null
              private var userRVAdapter: UserRVAdapter? = null
              private var userRV: RecyclerView? = null
              private var loadingPB: ProgressBar? = null
          
              override fun onCreate(savedInstanceState: Bundle?) {
                  super.onCreate(savedInstanceState)
                  setContentView(R.layout.activity_main)
                  userModalArrayList = ArrayList()
                  userRV = findViewById(R.id.idRVUsers)
                  loadingPB = findViewById(R.id.idPBLoading)
                  getDataFromAPI()
              }
          
              private fun getDataFromAPI() {
                  val url=
                "https://sheets.googleapis.com/v4/spreadsheets/YOUR_SHEET_ID/values/YOUR_SHEET_NAME?alt=json&key=YOUR_API_KEY"
                  val queue = Volley.newRequestQueue(this@MainActivity)
          
                  val jsonObjectRequest =
                      JsonObjectRequest(
                          Request.Method.GET,
                          url,
                          null,
                          object : Response.Listener<JSONObject> {
                              override fun onResponse(response: JSONObject) {
                                  loadingPB!!.visibility = View.GONE
                                  try {
                                      // val feedObj = response.getJSONObject("")
                                      val entryArray = response.getJSONArray("values")
          
                                      for (i in 1 until entryArray.length()) {
                                          val entryObj = entryArray.getJSONArray(i)
                                          val firstName =
                                              entryObj[2].toString()
                                          val lastName = entryObj[3].toString()
                                          //  entryObj.getJSONObject("gsx\$lastname").getString("\$t")
                                          val email = entryObj[1].toString()
          
                                          userModalArrayList!!.add(model(firstName, lastName, email))
          
          
                                          // passing array list to our adapter class.
                                          userRVAdapter = UserRVAdapter(userModalArrayList!!)
          
                                          // setting layout manager to our recycler view.
                                          userRV!!.layoutManager = LinearLayoutManager(this@MainActivity)
          
                                          // setting adapter to our recycler view.
                                          userRV!!.adapter = userRVAdapter
                                      }
                                  } catch (e: JSONException) {
                                      e.printStackTrace()
                                  }
                              }
                          },
                          object : Response.ErrorListener {
                              override fun onErrorResponse(error: VolleyError?) {
                                  // handline on error listener method.
                                  Toast.makeText(this@MainActivity, "Fail to get data..", Toast.LENGTH_SHORT)
                                      .show()
                              }
                          })
                  queue.add(jsonObjectRequest);
              }
          }
      

      您可以使用此代码从整个 google 电子表格中获取数据。

      【讨论】:

      • 请接受答案,以便其他用户可以了解该主题的基本思想。谢谢
      猜你喜欢
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多