【问题标题】:How to upload a blob (image) into a google sheet using google sheet api v 4如何使用 google sheet api v 4 将 blob(图像)上传到 google sheet
【发布时间】:2020-01-30 06:25:12
【问题描述】:

我有一个 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"}}

这是我们正在使用的 Web 应用程序。

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)  
}

【问题讨论】:

  • 1.我可以问你问题中的blob吗? 2. 遗憾的是,目前还没有直接用Sheets API 插入图片的方法。所以需要使用变通方法。我认为您问题中I have also looked at SO questions here. [Insert image into Google Sheets cell using Google Sheets API](https://stackoverflow.com/q/43664483) 的线程将解决您的问题。关于这个,我能问一下你目前的问题吗?
  • 如何在 GAE 中从我的 python 应用程序调用 SpreadsheetApp?
  • 感谢您的回复。我为我糟糕的英语水平道歉。如果您不能理解我的评论,请告诉我。我想修改它。
  • 我试图了解如何解决这个问题。函数 showImage() { var ss=SpreadsheetApp.getActiveSpreadsheet() var formulaSheet = ss.getSheetByName("Sheet1"); var formulaCell = formulaSheet.getRange("B5"); formulaCell.setFormula('=IMAGE("finviz.com/…) } 这是你推荐我实现的吗?
  • 感谢您的回复。如果您可以请求 POST 方法,我建议使用 Web 应用程序直接插入图像。因为在使用.setFormula('=IMAGE("finviz.com/…) 时,需要将上传的图片数据创建为文件并公开共享。所以我想推荐使用insertImage 和一个blob。在这种情况下,您可以将 base64 数据发送到 Web Apps,并将其作为图像插入到 Web Apps 的脚本中。为此,使用了 Google Apps 脚本。这对您的情况有用吗?

标签: google-apps-script google-sheets-api


【解决方案1】:

解决方案 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 脚本中的 insertImage 函数 [2],将网格图像插入到表格中,而不是链接到单元格的图像。您可以使用 doPost() 函数部署 Web 应用程序 [3],您可以在其中执行此操作并使用服务帐户凭据从 Python 应用程序调用 Web 应用程序。此外,您需要部署 Web 应用程序以作为“用户访问 Web 应用程序”执行,因此您从 Web 应用程序执行的所有请求都将使用服务帐户凭据进行。

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)

Web 应用脚本:

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->security->设置->高级设置->管理 API 客户端访问并使用服务帐户客户 ID。

[1]https://developers.google.com/sheets/api/guides/values

[2]https://developers.google.com/apps-script/reference/spreadsheet/sheet#insertImage(BlobSource,Integer,Integer)

[3]https://developers.google.com/apps-script/guides/web

【讨论】:

  • 关于方案二:do post方法可以被服务账号调用吗?怎么称呼它?什么是必要的凭据/权限等?
  • 是的,服务帐户身份验证是在 Python 脚本中进行的,该脚本在请求的“授权”标头中发送令牌,我们使用 google.auth2 库和 .json credentials file
猜你喜欢
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多