如何使用gspread将excel文件的属性保存到Google表格中?

问题描述 投票:0回答:1

我想将Excel文件上传到Google表格。手动地,我使用sheets.new网址创建工作表,然后单击导入,从本地计算机添加文件。

我想使它自动化,所以写了这段代码:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import csv


# use creds to create a client to interact with the Google Drive API
scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccountCredentials.from_json_keyfile_name(
    'client_secret.json', scope)
client = gspread.authorize(creds)

path = 'Use_Case_test_cliDependency_2.xlsx'
file_id = client.create('Use_Case_test_cliDependency_2')
print('File ID is: {}'.format(file_id.id))
print('URL is: {}'.format(file_id.url))
content = pd.read_excel(path)
csv_path = path.split('.xlsx')[0]+'.csv'
content.to_csv(csv_path, index=False)
content = open(csv_path, 'r').read()
client.import_csv(file_id.id, content.encode('utf-8'))
print('Check client')
client.insert_permission(file_id.id, None, perm_type='anyone', role='reader')

此代码成功运行,但是运行此代码时,我在excel工作表中显示的所有箭头都消失了。因此,如何像本手册一样保留Excel工作表的属性?

通过属性,我的意思是包括粗体,深色边缘等

python-3.x excel pandas google-drive-api gspread
1个回答
0
投票

我相信您的目标如下。

  • 您想将XLSX文件作为Google电子表格上传到Google云端硬盘。
    • 在当前情况下,用pd.read_excel(path)检索XLSX文件的内容,并将数据作为CSV数据放入。在这种情况下,当您手动将XLSX文件转换为Google Spreadsheet时,将删除所有格式的XLSX,而不会删除所有格式。
    • 您想在不删除格式的情况下将XLSX文件转换为Google Spreadsheet。
  • 您想通过gspread和python实现此目的。
  • 您已经能够使用Sheets API和Drive API获取和放置Google Spreadsheet和Google Drive的值。

为此,这个答案如何?

修改点:

  • 为了保持XLSX文件的格式,在此修改中,上传文件时,使用Drive API将XLSX文件转换为Google Spreadsheet。这样,我认为当XLSX转换为Google Spreadsheet时,格式会保留。

修改的脚本:

修改脚本后,将如下所示。

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import csv
import requests
import json

# use creds to create a client to interact with the Google Drive API
scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccountCredentials.from_json_keyfile_name(
    'client_secret.json', scope)
client = gspread.authorize(creds)
path = 'Use_Case_test_cliDependency_2.xlsx'
spreadsheet_name = 'Use_Case_test_cliDependency_2'

# Upload XLSX file by converting to Google Spreadsheet.
url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'
headers = {'Authorization': 'Bearer ' + client.auth.token}
metadata = {'name': spreadsheet_name, 'mimeType': 'application/vnd.google-apps.spreadsheet'}
files = {
    'data': ('metadata', json.dumps(metadata), 'application/json; charset=UTF-8'),
    'file': open(path, 'rb')
}
res = requests.post(url, headers=headers, files=files)
obj = res.json()
fileId = obj['id']

# Create permission.
client.insert_permission(fileId, None, perm_type='anyone', role='reader')
  • 在这种情况下,通过使用Drive API中的文件创建方法将requests转换为Google Spreadsheet,可以将XLSX文件上传到Google Drive。

注意:

  • 在此方法中,最大文件大小为5 MB。请注意这一点。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.