【问题标题】:How to convert Azure Blob file CSV to Excel in Python如何在 Python 中将 Azure Blob 文件 CSV 转换为 Excel
【发布时间】:2021-12-26 02:55:51
【问题描述】:

我正在尝试将 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)

关于如何实现这一点的任何建议?

【问题讨论】:

    标签: python azure azure-blob-storage


    【解决方案1】:

    您可以使用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)
    

    参考文献

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2020-12-28
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 2014-11-19
      相关资源
      最近更新 更多