如何使用Google表格API V4导入CSV文件

ida*_*hmu 7 python-2.7 google-spreadsheet-api google-sheets-api

背景

我正在开发一个Python 2.7脚本来分析SQL表中的数据,最后生成一个CSV文件.

生成文件后,我正在登录我的Google工作表帐户并使用导入选项将我的CSV文件导入到Google电子表格中

手工劳动有点愚蠢,我希望将这种能力添加到我的脚本中.

Google表格API V4

所以,我按照本指南Python Quickstart完成了所有步骤.

然后我按照Google表格API参考并查看了Method:spreadsheets.create.如果我理解正确,它不提供从文件导入的选项.

似乎没有用于导入功能的API.

如何使用Google表格API V4导入CSV文件?他们是我失踪的榜样/参考吗?

Ufo*_*fos 14

我花了几个小时试图使任何其他答案起作用。图书馆不能很好地解释身份验证,并且不能使用谷歌提供的处理凭据的方式。另一方面,Sam 的回答没有详细说明使用 API 的细节,这有时可能会令人困惑。因此,这是将 CSV 上传到 gSheets 的完整方法。它使用了 Sam 和 CapoChino 的答案以及我自己的一些研究。

  1. 验证/设置。一般来说,参考文档
    • 蓝色大按钮credentials.json无需额外步骤即可帮助您
    • quickstart.py 可以很容易地适应 authenticate.py
    • 范围应包含 https://www.googleapis.com/auth/spreadsheets

希望现在您已经存储了您的凭据,所以让我们转到实际代码

  1. 应该开箱即用的食谱:
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)
)
Run Code Online (Sandbox Code Playgroud)

直接使用的好处batchUpdate是它可以在一秒钟内上传数千行。在低级别上gspread做同样的事情并且应该是高性能的。还有gspread-pandas

ps 代码是用 python 测试的3.5,但这个线程似乎最适合提交它。


Sam*_*lin 12

您有两种导入g CSV文件的选项.您可以使用驱动API从CSV创建一个电子表格,或者您可以使用表API来创建一个空的电子表格,然后使用spreadsheets.batchUpdatePasteDataRequest添加CSV数据.

  • 想要更多关于如何使用 PasteDataRequest 进行批量更新的信息!文档很少:/ (2认同)
  • 令人沮丧的是,这些信息 - “使用 PasteDataRequest” - 没有包含在 Sheets API 的文档中。 (2认同)

Bur*_*ash 5

Sam Berlin答案的另一种选择。如果您使用 Python,则可以通过gspread使用 Drive 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)
Run Code Online (Sandbox Code Playgroud)

相关问题:使用 gspread 将 CSV 上传到 Google 表格

  • **注意** 此方法会删除所有其他工作表,然后完全替换第一个工作表的内容。 (3认同)

小智 5

我喜欢 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)
Run Code Online (Sandbox Code Playgroud)

请注意,我使用原始 pasteData 请求而不是更高级别的update_cells方法来利用 Google 自动(正确)处理包含引号字符串的输入数据,其中可能包含非分隔符逗号。