使用Python从Smartsheet复制单元格图像

时间:2018-02-13 19:10:56

标签: python excel smartsheet-api

我正在尝试在本地磁盘上制作智能表数据的副本。我能够复制除细胞图像以外的所有智能表数据。以下是我正在使用的代码。此代码完全可以复制数据,但不能复制单元格图像 注意:我不是要从智能表中复制附件;只有细胞的图像和数据。 有人可以帮助我增强此代码以复制单元格图像吗?

import json
import os
import requests
import time


token = "Bearer <TOken>"


backed_up_sheets = {"Attach": 86960044478894,"test2":6659760455684}

dir = r'C:\Users\\me\SmartSheetsBackup\WorkSheet' + time.strftime("-%m_%d_%Y_%H_%M")

API_URL = "https://api.smartsheet.com/2.0/sheets/"

payload = {"Authorization": token,
           "Accept": "application/vnd.ms-excel,image/*"}


amount = len(backed_up_sheets)

i = 1
for el in backed_up_sheets:
    r = requests.get(API_URL + str(backed_up_sheets[el]) , headers=payload)
    if r.status_code != 200:
        print ('Some problem with connections please retry later0')
        pass
    if not os.path.exists(dir):
       os.makedirs(dir)

    with open(dir + el + time.strftime("-%m_%d_%Y_%H_%M") +  ".xlsx", 'wb') as output:
        output.write(r.content)
    print ('Progress in sheets: ' + str(i) + '/' + str(amount))
    i += 1

2 个答案:

答案 0 :(得分:0)

cURL示例中说明的相同步骤应该适用于Python。 (抱歉,我们没有完整的已发表样本)

  1. get_sheet
  2. 返回的单元格对象中获取图片ID
  3. 使用images.get_image_urlsdocs
  4. 将图片ID转换为下载网址
  5. 可能使用Requests库从网址下载图片。

答案 1 :(得分:0)

这是一个完整的代码示例:

# Download an image in a cell
def download_cell_image(client, sheet_id, row_id, column_id, default_filename):
    # Get desired row
    row = client.Sheets.get_row(sheet_id, row_id)
    cell = row.get_column(column_id)
    image = cell.image

    filename = getattr(image, 'alt_text', default_filename)

    # Obtain a temporary image URL
    imageUrl = ss_client.models.ImageUrl( { "imageId": image.id } ) 
    response = ss_client.Images.get_image_urls([imageUrl])
    url = response.image_urls[0].url

   # Download the image
    import requests
    response = requests.get(url)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)

请注意,这需要SDK 1.3.0或更高版本