📜  在Python中使用 Google Sheets 作为数据库

📅  最后修改于: 2022-05-13 01:55:06.611000             🧑  作者: Mango

在Python中使用 Google Sheets 作为数据库

在本文中,我们将讨论如何使用 Google Sheets 像数据库一样运行任何Python文件。

谷歌电子表格:

Google 电子表格是免费的基于网络的在线应用程序,类似于 Microsoft Excel。您可以使用它为各种项目创建和编辑表格,例如联系人列表、预算以及您可以想象的几乎所有内容。

Google 电子表格(突出显示的是工具栏)

应用程序接口:

连通性是一件非常重要的事情,我们都习惯了即时连通性,它让世界在我们的桌面或移动设备上触手可及。那么数据如何从 A 点传输到 B 点,不同的设备和应用程序如何相互连接。 API 是接收请求并告诉系统您想要做什么并将响应返回给您的信使。

谷歌电子表格 API:

我们可以将此 Google 电子表格用作数据存储,您可以通过 API 访问此数据存储,因此我们可以做的是将数据放入我们的应用程序中,您可以将数据作为常规 JSON API 访问。

循序渐进的方法:

  • 因此,我们的第一步是在您的任何 Google 帐户上创建一个电子表格并为其取一个合适的名称,就像我们可以使用一些随机条目命名Google Sheets API 教程,如下所示:

谷歌表格

  • 下一步访问 Google Cloud Platform 现在会打开一个页面,如下所示:

谷歌云平台

  • 现在单击我的第一个项目出现以下对话框,现在单击新建项目

  • 现在创建您的项目。现在点击侧边菜单栏中的API & Services然后转到如下所示的 Library 并搜索Google Drive并点击Google Drive API

单击启用

  • 现在我们要下载一个JSON文件来存储我们的凭据,所以一旦下载,我们将返回库并搜索 Google Sheets API,启用它,一旦启用我们都准备用我们的代码连接一些东西这就是我们的 Google Cloud Platform,只需确保跟踪JSON文件的位置,因为我们现在实际上要打开它。

creds.json

  • 现在我们要复制客户电子邮件,然后转到我们之前制作的 Google 表格,转到共享选项,将该电子邮件粘贴到其中,然后单击发送。这允许从我们的 API 访问 Google 表格。不,我们现在将回到Pycharm ,并创建一个Python文件sheet.py

  • 现在我们将回到Pycharm ,并创建一个Python文件sheet.py。现在我们没有编写任何代码,但我们将使用pip安装两个包或模块,以便我们可以实际使用 API,因此在Pycharm中我们只需打开内置终端,或者我们可以打开命令提示符并键入下面的命令:
pip install gspread oauth2client 

  • 完成后,您需要使用一些模块创建一个Python脚本。下面是完整的程序:
Python3
# Import required modules
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
  
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
         "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
  
  
  
# Assign credentials ann path of style sheet
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
sheet = client.open("Google Sheets API Tutorial").sheet1
  
  
  
# Sisplay data
data = sheet.get_all_records()
row4 = sheet.row_values(4)
col2 = sheet.col_values(2)
cell = sheet.cell(5, 2).value
  
print("Column 2 Data : ")
pprint(col2)
print("\nRow 4 Data : ")
pprint(row4)
print("\nCell (5,2) Data : ")
pprint(cell)
print("\nAll Records : ")
pprint(data)
  
  
  
# Inserting data
insertRow = [6, "Soumodeep Naskar", "Purple"]
sheet.insert_row(insertRow, 4)
print("\nAll Records after inserting new row : ")
pprint(data)
  
  
  
# Deleting data
sheet.delete_row(7)
print("\nAll Records after deleting row 7 : ")
pprint(data)
  
  
  
# Update a cell
sheet.update_cell(5, 2, "Nitin Das")
print("\nAll Records after updating cell (5,2) : ")
pprint(data)
  
  
  
# Display no. of rows, columns 
# and no. of rows having content
numRows = sheet.row_count
numCol = sheet.col_count
print("Number of Rows : ", numRows)
print("Number of Columns : ", numCol)
print("Number of Rows having content : ", len(data))


输出: