我有一个Blob数据。我想使用Google Sheet API v4将其上传到Google Sheet中的单元格。
我在这里查看了文档。 https://developers.google.com/sheets/api/guides/values
我也在这里查看了SO问题。 Insert image into Google Sheets cell using Google Sheets API
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id, range=range_name,
valueInputOption=value_input_option, body=body).execute()
我没有看到描述将Blob作为图像插入的任何服务。请帮忙。
根据以下建议,我们从此处实现了Webapp-Insert image into Google Sheets cell using Google Sheets API
这就是我们从python代码调用网络应用的方式
dropoff_signature = "ZGF0YT <clip > WVhSaA=="
web_app_url = "https://script.google.com/macros/s/A < clip > y/exec"
image_data = "data:image/png;base64," + dropoff_signature
data_to_post = {
'spreadsheetid' : spreadsheet_Id,
'sheetname' : 'Sheet1',
'imageurl' : image_data,
'column' : 5,
'row' : 5
}
encoded_data = urllib.urlencode(data_to_post)
# Send encoded data to application-2
url_result = urlfetch.fetch(web_app_url, encoded_data, method='POST')
我们在Web应用程序中看到以下错误。
result : 200 content : {"status":"error","defaultMessage":"Error retrieving image from URL or bad URL: data:image/png;base64, <clip> ","name":"Exception","fileName":"Code (Insert image into spreadsheet)","lineNumber":42,"stack":"\tat Code (Insert image into spreadsheet):42 (doPost)\n"}}
可以帮忙吗?
进行此更改。仍然出现错误的URL错误。
dropoff_signature = "ZGF0YTpp<clip>WVhSaA=="
web_app_url = "https://script.google.com/macros/s/A<clip>y/exec"
image_data = "data:image/png;base64," + dropoff_signature
data_to_post = {
'spreadsheetid' : spreadsheet_Id,
'sheetname' : 'Sheet1',
'imageurl' : image_data,
'column' : 5,
'row' : 5
}
# encoded_data = urllib.urlencode(data_to_post)
# Send encoded data to application-2
# url_result = urlfetch.fetch(web_app_url, encoded_data, method='POST')
url_result = urlfetch.fetch(url=web_app_url, payload=json.dumps(data_to_post), method='POST', headers={'Content-type': 'application/json'})
result : 200 content : {"status":"error","defaultMessage":"Error retrieving
image from URL or bad URL:
data:image/png;base64,Z<clip>A==","error":
{"message":"Error retrieving image from URL or bad URL: data:image/png;base64,Z<clip>A==","name":"Exception","fileName":"Code (Insert image into spreadsheet)","lineNumber":42,"stack":"\tat Code (Insert image into spreadsheet):42 (doPost)\n"}}
这是我们正在使用的Webapp。
function doGet(e) {
return ContentService.createTextOutput("Authorization: Bearer " +
ScriptApp.getOAuthToken())
}
//
// Example curl command to insert an image:
//
// curl -L -d '{ "spreadsheetid": "1xNDWJXOekpBBV2hPseQwCRR8Qs4LcLOcSLDadVqDA0E","sheetname": "Sheet1", "imageurl": "https://www.google.com/images/srpr/logo3w.png", "column": 1, "row": 1 }' \
// -H "Authorization: Bearer <INSERT TOKEN RETURNED FROM GET HERE>" \
// -H 'Content-Type: application/json' \
// https://script.google.com/a/tillerhq.com/macros/s/AKfycbzjFgIrgCfZTvOHImuX54G90VuAgmyfz2cmaKjrsNFrTzcLpNk0/exec
//
var REQUIRED_PARAMS = [
'spreadsheetid', // example: "1xNDWJXOekpBBV2hPseQwCRR8Qs4LcLOcSLDadVqDA0E"
'sheetname', // Case-sensitive; example: "Sheet1"
'imageurl', // Can be an url such as "https://www.google.com/images/srpr/logo3w.png"
// or alternately "data:image/png;base64,iVBOR...<snip>...gg=="
'column', // 1-based (i.e. top left corner is column 1)
'row' // 1-based (i.e. top left corner is row 1)
];
function doPost(e) {
var result = {
status: "ok",
defaultMessage: "Image inserted."
}
try {
var params = (e.postData && e.postData.type == "application/x-www-form-urlencoded") ? e.parameter
: (e.postData && e.postData.type == "application/json") ? JSON.parse(e.postData.contents)
: undefined;
if (!params) throw new Error('Unsupported content-type, must be either application/x-www-form-urlencoded or application/json.');
REQUIRED_PARAMS.forEach(function(requiredParam) {
if (!params[requiredParam]) throw new Error('Missing required parameter ' + requiredParam);
});
SpreadsheetApp.openById(params.spreadsheetid).getSheetByName(params.sheetname).insertImage(params.imageurl, params.column, params.row);
} catch(e) {
console.error(e);
result.status = "error";
result.error = e;
result.defaultMessage = e.message;
}
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON)
}
答案 0 :(得分:0)
解决方案1:
在Python应用程序中,您可以使用以下代码使用Sheets API [1]通过IMAGE公式设置图像。您需要输入电子表格ID并更改所需图像的范围。
spreadsheet_id = '[SPREADSHEET-ID]'
range_name = 'D13'
service = build('sheets', 'v4', credentials=creds)
values = [
[
'=IMAGE("https://google.com","google")'
]
]
body = {
'values': values
}
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id, range=range_name,
valueInputOption='USER_ENTERED', body=body).execute()
解决方案2:
如果相反,您想使用Apps Script中的insertImage函数[2],则将网格上方的图像插入到表格中,而不是链接到单元格的图像。您可以部署具有doPost()函数的Web应用程序[3],在其中可以执行此操作,并使用服务帐户凭据从Python应用程序中调用Web应用程序。另外,您还需要部署Web应用程序,使其以“用户访问Web应用程序”的身份执行,这样您从Web App发出的所有请求都将使用服务帐户凭据发出。
Python脚本:
from google.oauth2 import service_account
import requests
import json
import google.auth.transport.requests
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'service_account.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject('[USER-EMAIL-TO-IMPERSONATE]')
delegated_credentials.refresh(google.auth.transport.requests.Request())
token = delegated_credentials.token
headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + token}
url = '[WEB-APP-URL]'
data = {"file": '[blob]'}
response = requests.post(url, data=json.dumps(data), headers=headers)
网络应用脚本:
function doPost(e) {
var ss = SpreadsheetApp.openById('[SPREADSHEET-ID]');
var sheet = ss.getSheets()[0];
var blob = DriveApp.getFileById("[IMAGE-ID]").getBlob();
sheet.insertImage(blob, 4, 14);
return ContentService.createTextOutput("Good");
}
我使用从Web应用程序中的云端硬盘获取的图像测试了我的代码。您可以跳过这一部分,直接从Python应用程序的数据有效载荷中发送blob。
要使用服务帐户,请记住要授予对所有所需范围的API访问权限,您需要转到admin.google.com->安全性->设置->高级设置->管理API客户端访问权限并使用服务帐户客户编号。