我想将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工作表的属性?
通过属性,我的意思是包括粗体,深色边缘等
我相信您的目标如下。
pd.read_excel(path)
检索XLSX文件的内容,并将数据作为CSV数据放入。在这种情况下,当您手动将XLSX文件转换为Google Spreadsheet时,将删除所有格式的XLSX,而不会删除所有格式。为此,这个答案如何?
修改脚本后,将如下所示。
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')
requests
转换为Google Spreadsheet,可以将XLSX文件上传到Google Drive。