python - 如何在 Python 中将 Azure Blob 文件 CSV 转换为 Excel

标签 python azure azure-blob-storage

我正在尝试将 Azure 存储容器中的 CSV 文件转换为 EXCEL 并将其放置在同一个容器中。

我可以使用以下代码从 CSV 文件读取数据,但无法将其转换为 Excel 并将其上传到容器中。

from io import StringIO
from azure.storage.blob import BlobServiceClient, ContainerClient, BlobClient
from typing import Container
import pandas as pd

conn_str = "DefaultEndpointsProtocol=https;AccountName="";AccountKey="";EndpointSuffix="""
container = "testing"
blob_name = "Test.csv"
filename = "test.xlsx"

container_client = ContainerClient.from_connection_string(
conn_str=conn_str, 
container_name=container
)   

downloaded_blob = container_client.download_blob(blob_name)

read_file = pd.read_csv(StringIO(downloaded_blob.content_as_text()) )

print(read_file)

关于如何实现这一目标有什么建议吗?

最佳答案

您可以使用 to_excel API 将 pandas 数据框(read_file)转换为 Excel 文件。由于您想将其上传到 blob 存储中,因此可以先将其写入内存缓冲区。

import pandas as pd
from io import BytesIO

buffer = BytesIO()

# By setting the 'engine' in the ExcelWriter constructor.
writer = pd.ExcelWriter(buffer, engine="xlsxwriter")
# 'read_file' is your pandas DataFrame
read_file.to_excel(writer, sheet_name="Sheet1") 

# Save the workbook
writer.save()

# Seek to the beginning 
buffer.seek(0)

buffer 现在已准备好上传到 Blob 存储的数据。因此,您可以先创建一个blob客户端实例,然后使用upload_blob方法上传excel文件。如果要覆盖 Azure 中的文件,还需设置 overwrite=True

excel_blob_client = BlobClient.from_connection_string(
conn_str=conn_str, 
container_name=container,
blob_name = "test.xlsx"
)  
excel_blob_client.upload_blob(buffer, overwrite=True)

引用文献

关于python - 如何在 Python 中将 Azure Blob 文件 CSV 转换为 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69965283/

相关文章:

python - Pandas 根据条件交换列

python - 如何从python3中的pandas数据框中选择特定时间范围的列?

Azure CosmosDB - 分区键达到最大大小 10 GB

.net - Xamarin 身份验证 - 用户已弃用,迁移到 IAccount 时出现问题

visual-studio - 如何使用 Visual Code studio 在 azure 上部署静态网站?

node.js - Azure Blob 服务 REST API - 错误 : read ECONNRESET

python - 从动态数组中构造一个带有新行的字符串

python - 如何将关键字参数传递给 reactor.callLater

powershell - 与 Microsoft Azure AD 模块 PowerShell 和 Microsoft Azure Powershell 的不同之处

python - 如何使用 Python 中 Azure Functions 的 Azure Blob 存储绑定(bind)将 JSON 数据上传到 Azure 存储 Blob