如何使用 Google Sheets API V4 导入 CSV 文件
How to import a CSV file using Google Sheets API V4
背景
我正在开发一个 Python 2.7
脚本来分析来自 SQL table 的数据并在最后生成一个 CSV 文件。
文件生成后,我将登录我的 google sheet 帐户并使用导入选项将我的 CSV 文件导入 google 传播sheet
体力劳动有点愚蠢,我希望将此功能添加到我的脚本中。
Google 张 API V4
因此,我遵循了本指南,Python Quickstart 并且能够完成所有步骤。
然后我关注了Google Sheets API reference and looked into Method: spreadsheets.create。如果我没理解错的话,它没有提供从文件导入的选项。
似乎没有API导入功能。
问题
如何使用 Google Sheets API V4 导入 CSV 文件?他们是我想念的 example/reference 吗?
您有两种导入 g CSV 文件的选项。您可以使用 Drive API to create a spreadsheet from a CSV, or you can use the Sheets API to create an empty spreadsheet and then use spreadsheets.batchUpdate with a PasteDataRequest 添加 CSV 数据。
替代 Sam Berlin 的答案,您可以将 CSV 转换为列表列表并将其设置为您的 POST 负载。
这样的函数看起来像这样:
def preprocess(table):
table.to_csv('pivoted.csv') # I use Pandas but use whatever you'd like
_file = open('pivoted.csv')
contents = _file.read()
array = contents.split('\n')
master_array = []
for row in array:
master_array.append(row.split(','))
return master_array
那个主数组被扔到下面:
body = {
'values': newValues
}
result2 = service.spreadsheets().values().update(spreadsheetId=spreadsheetId, range=rangeName + str(len(values) + start + 1), valueInputOption="USER_ENTERED", body=body).execute()
对我来说效果很好。
Sam Berlin 答案的另一种选择。如果您使用的是 Python,则可以通过 gspread 使用驱动器 API 来导入 CSV 文件。这是一个例子:
import gspread
# Check how to get `credentials`:
# https://github.com/burnash/gspread
gc = gspread.authorize(credentials)
# Read CSV file contents
content = open('file_to_import.csv', 'r').read()
gc.import_csv('<SPREADSHEET_ID>', content)
相关问题:Upload CSV to Google Sheets using gspread
我喜欢 Burnash 的 gspread 库,但他的回答中的 import_csv
功能有限。它总是从第一个工作表(选项卡) 的 A1
处开始粘贴,并删除所有其他选项卡。
我需要从特定的选项卡和单元格开始粘贴,所以我采纳了 Sam Berlin 的建议使用 PasteDataRequest。这是我的函数:
def pasteCsv(csvFile, sheet, cell):
'''
csvFile - path to csv file to upload
sheet - a gspread.Spreadsheet object
cell - string giving starting cell, optionally including sheet/tab name
ex: 'A1', 'MySheet!C3', etc.
'''
if '!' in cell:
(tabName, cell) = cell.split('!')
wks = sheet.worksheet(tabName)
else:
wks = sheet.sheet1
(firstRow, firstColumn) = gspread.utils.a1_to_rowcol(cell)
with open(csvFile, 'r') as f:
csvContents = f.read()
body = {
'requests': [{
'pasteData': {
"coordinate": {
"sheetId": wks.id,
"rowIndex": firstRow-1,
"columnIndex": firstColumn-1,
},
"data": csvContents,
"type": 'PASTE_NORMAL',
"delimiter": ',',
}
}]
}
return sheet.batch_update(body)
请注意,我使用原始 pasteData 请求而不是更高级别的 update_cells
方法来利用 Google 对包含引号字符串的输入数据的自动(正确)处理,这可能包含非分隔符逗号。
我花了几个小时试图使任何其他答案有效。图书馆没有很好地解释身份验证,并且不能使用 google 提供的处理凭据的方式。
另一方面,Sam 的回答没有详细说明使用 API 的细节,这有时可能会让人感到困惑。
因此,这是将 CSV 文件上传到 gSheets 的完整方法。它使用了 Sam 和 CapoChino 的答案以及我自己的一些研究。
- Authenticate/Setup。一般参考docs
- 蓝色大按钮
credentials.json
无需额外步骤
quickstart.py
可以很容易地改编成authenticate.py
- 范围应包含
https://www.googleapis.com/auth/spreadsheets
希望现在您已经存储了您的凭据,所以让我们转到实际代码
- 开箱即用的配方:
import pickle
from googleapiclient.discovery import build
SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' # Get this one from the link in browser
worksheet_name = 'Sheet2'
path_to_csv = 'New Folder/much_data.csv'
path_to_credentials = 'Credentials/token.pickle'
# convenience routines
def find_sheet_id_by_name(sheet_name):
# ugly, but works
sheets_with_properties = API \
.spreadsheets() \
.get(spreadsheetId=SPREADSHEET_ID, fields='sheets.properties') \
.execute() \
.get('sheets')
for sheet in sheets_with_properties:
if 'title' in sheet['properties'].keys():
if sheet['properties']['title'] == sheet_name:
return sheet['properties']['sheetId']
def push_csv_to_gsheet(csv_path, sheet_id):
with open(csv_path, 'r') as csv_file:
csvContents = csv_file.read()
body = {
'requests': [{
'pasteData': {
"coordinate": {
"sheetId": sheet_id,
"rowIndex": "0", # adapt this if you need different positioning
"columnIndex": "0", # adapt this if you need different positioning
},
"data": csvContents,
"type": 'PASTE_NORMAL',
"delimiter": ',',
}
}]
}
request = API.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=body)
response = request.execute()
return response
# upload
with open(path_to_credentials, 'rb') as token:
credentials = pickle.load(token)
API = build('sheets', 'v4', credentials=credentials)
push_csv_to_gsheet(
csv_path=path_to_csv,
sheet_id=find_sheet_id_by_name(worksheet_name)
)
直接使用 batchUpdate
的好处是它可以在一秒钟内上传数千行。在低级别上 gspread
做同样的事情并且应该是高性能的。还有gspread-pandas。
p.s。代码是用 python 3.5
测试的,但是这个线程似乎最适合提交它。
背景
我正在开发一个 Python 2.7
脚本来分析来自 SQL table 的数据并在最后生成一个 CSV 文件。
文件生成后,我将登录我的 google sheet 帐户并使用导入选项将我的 CSV 文件导入 google 传播sheet
体力劳动有点愚蠢,我希望将此功能添加到我的脚本中。
Google 张 API V4
因此,我遵循了本指南,Python Quickstart 并且能够完成所有步骤。
然后我关注了Google Sheets API reference and looked into Method: spreadsheets.create。如果我没理解错的话,它没有提供从文件导入的选项。
似乎没有API导入功能。
问题
如何使用 Google Sheets API V4 导入 CSV 文件?他们是我想念的 example/reference 吗?
您有两种导入 g CSV 文件的选项。您可以使用 Drive API to create a spreadsheet from a CSV, or you can use the Sheets API to create an empty spreadsheet and then use spreadsheets.batchUpdate with a PasteDataRequest 添加 CSV 数据。
替代 Sam Berlin 的答案,您可以将 CSV 转换为列表列表并将其设置为您的 POST 负载。
这样的函数看起来像这样:
def preprocess(table):
table.to_csv('pivoted.csv') # I use Pandas but use whatever you'd like
_file = open('pivoted.csv')
contents = _file.read()
array = contents.split('\n')
master_array = []
for row in array:
master_array.append(row.split(','))
return master_array
那个主数组被扔到下面:
body = {
'values': newValues
}
result2 = service.spreadsheets().values().update(spreadsheetId=spreadsheetId, range=rangeName + str(len(values) + start + 1), valueInputOption="USER_ENTERED", body=body).execute()
对我来说效果很好。
Sam Berlin 答案的另一种选择。如果您使用的是 Python,则可以通过 gspread 使用驱动器 API 来导入 CSV 文件。这是一个例子:
import gspread
# Check how to get `credentials`:
# https://github.com/burnash/gspread
gc = gspread.authorize(credentials)
# Read CSV file contents
content = open('file_to_import.csv', 'r').read()
gc.import_csv('<SPREADSHEET_ID>', content)
相关问题:Upload CSV to Google Sheets using gspread
我喜欢 Burnash 的 gspread 库,但他的回答中的 import_csv
功能有限。它总是从第一个工作表(选项卡) 的 A1
处开始粘贴,并删除所有其他选项卡。
我需要从特定的选项卡和单元格开始粘贴,所以我采纳了 Sam Berlin 的建议使用 PasteDataRequest。这是我的函数:
def pasteCsv(csvFile, sheet, cell):
'''
csvFile - path to csv file to upload
sheet - a gspread.Spreadsheet object
cell - string giving starting cell, optionally including sheet/tab name
ex: 'A1', 'MySheet!C3', etc.
'''
if '!' in cell:
(tabName, cell) = cell.split('!')
wks = sheet.worksheet(tabName)
else:
wks = sheet.sheet1
(firstRow, firstColumn) = gspread.utils.a1_to_rowcol(cell)
with open(csvFile, 'r') as f:
csvContents = f.read()
body = {
'requests': [{
'pasteData': {
"coordinate": {
"sheetId": wks.id,
"rowIndex": firstRow-1,
"columnIndex": firstColumn-1,
},
"data": csvContents,
"type": 'PASTE_NORMAL',
"delimiter": ',',
}
}]
}
return sheet.batch_update(body)
请注意,我使用原始 pasteData 请求而不是更高级别的 update_cells
方法来利用 Google 对包含引号字符串的输入数据的自动(正确)处理,这可能包含非分隔符逗号。
我花了几个小时试图使任何其他答案有效。图书馆没有很好地解释身份验证,并且不能使用 google 提供的处理凭据的方式。 另一方面,Sam 的回答没有详细说明使用 API 的细节,这有时可能会让人感到困惑。 因此,这是将 CSV 文件上传到 gSheets 的完整方法。它使用了 Sam 和 CapoChino 的答案以及我自己的一些研究。
- Authenticate/Setup。一般参考docs
- 蓝色大按钮
credentials.json
无需额外步骤 quickstart.py
可以很容易地改编成authenticate.py
- 范围应包含
https://www.googleapis.com/auth/spreadsheets
- 蓝色大按钮
希望现在您已经存储了您的凭据,所以让我们转到实际代码
- 开箱即用的配方:
import pickle
from googleapiclient.discovery import build
SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' # Get this one from the link in browser
worksheet_name = 'Sheet2'
path_to_csv = 'New Folder/much_data.csv'
path_to_credentials = 'Credentials/token.pickle'
# convenience routines
def find_sheet_id_by_name(sheet_name):
# ugly, but works
sheets_with_properties = API \
.spreadsheets() \
.get(spreadsheetId=SPREADSHEET_ID, fields='sheets.properties') \
.execute() \
.get('sheets')
for sheet in sheets_with_properties:
if 'title' in sheet['properties'].keys():
if sheet['properties']['title'] == sheet_name:
return sheet['properties']['sheetId']
def push_csv_to_gsheet(csv_path, sheet_id):
with open(csv_path, 'r') as csv_file:
csvContents = csv_file.read()
body = {
'requests': [{
'pasteData': {
"coordinate": {
"sheetId": sheet_id,
"rowIndex": "0", # adapt this if you need different positioning
"columnIndex": "0", # adapt this if you need different positioning
},
"data": csvContents,
"type": 'PASTE_NORMAL',
"delimiter": ',',
}
}]
}
request = API.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=body)
response = request.execute()
return response
# upload
with open(path_to_credentials, 'rb') as token:
credentials = pickle.load(token)
API = build('sheets', 'v4', credentials=credentials)
push_csv_to_gsheet(
csv_path=path_to_csv,
sheet_id=find_sheet_id_by_name(worksheet_name)
)
直接使用 batchUpdate
的好处是它可以在一秒钟内上传数千行。在低级别上 gspread
做同样的事情并且应该是高性能的。还有gspread-pandas。
p.s。代码是用 python 3.5
测试的,但是这个线程似乎最适合提交它。