【发布时间】:2020-11-04 13:58:25
【问题描述】:
我想将存储在 Azure blob 存储中的 excel 文件读取到 python 数据框。我会使用什么方法?
【问题讨论】:
标签: python azure-functions azure-blob-storage azure-blob-trigger
我想将存储在 Azure blob 存储中的 excel 文件读取到 python 数据框。我会使用什么方法?
【问题讨论】:
标签: python azure-functions azure-blob-storage azure-blob-trigger
pandas包中有一个名为read_excel的函数,可以将在线excel文件的url传给函数,获取excel表的dataframe,如下图。
所以你只需要生成一个带有 sas 令牌的 excel blob 的 url,然后将它传递给函数。
这是我的示例代码。注意:需要安装Python包azure-storage、pandas和xlrd。
# Generate a url of excel blob with sas token
from azure.storage.blob.baseblobservice import BaseBlobService
from azure.storage.blob import BlobPermissions
from datetime import datetime, timedelta
account_name = '<your storage account name>'
account_key = '<your storage key>'
container_name = '<your container name>'
blob_name = '<your excel blob>'
blob_service = BaseBlobService(
account_name=account_name,
account_key=account_key
)
sas_token = blob_service.generate_blob_shared_access_signature(container_name, blob_name, permission=BlobPermissions.READ, expiry=datetime.utcnow() + timedelta(hours=1))
blob_url_with_sas = blob_service.make_blob_url(container_name, blob_name, sas_token=sas_token)
# pass the blob url with sas to function `read_excel`
import pandas as pd
df = pd.read_excel(blob_url_with_sas)
print(df)
我使用我的示例 excel 文件来测试下面的代码,它工作正常。
图 1. 我在 Azure Blob 存储的 test 容器中的示例 excel 文件 testing.xlsx
图2.我的示例excel文件testing.xlsx的内容
图 3. 我的示例 Python 代码读取 excel blob 的结果
【讨论】:
from azure.storage.blob.baseblobservice import BaseBlobService