Search code examples
pythonexcelioazure-functionsazure-blob-trigger

How to uploade an Excel file to a Blob Storage as an Excel File


i have a process that's beening triggered by Blobs. I'm trying to upload a dataframe to Azure blob storage and i can achieve this via this code.

async def main(myblob: func.InputStream,  outputblob: func.Out[str]) -> None:
(Some Code)
outputblob.set(Buch.to_string())

but the problem with that approach is that it uploads the DataFrames as a File and not as CSV or Excel file. I also tried this Code but this time nothing was uploaded.

outputblob.set(Deb.to_excel("Deb.xlsx"))

Is there anyway that we can uploade as Excel files?


Solution

  • the Solution is to upload it manually without using the Built-in function:

    outputblob.set()
    

    my code for uploading a CSV file to a container. works for HTTP and Blob Trigger.

    def upload(_file,_connectionString,_containerName,_fileName):            
            blob_service_client = BlobServiceClient.from_connection_string(_connectionString)
            # Instantiate a new ContainerClient
            container_client = blob_service_client.get_container_client(_containerName)
            if not container_client.exists():
                # Create new Container in the service
                print("container does not exist. create it")
                container_client.create_container()
                properties = container_client.get_container_properties()
                # Instantiate a new BlobClient            
                blob_client = container_client.get_blob_client(_fileName)
                # upload data
                blob_client.upload_blob(_file, blob_type="BlockBlob")
            else:
                blob = BlobClient.from_connection_string(conn_str=_connectionString,
                                                        container_name=_containerName,
                                                        blob_name=_fileName) 
                if blob.exists():
                    logging.info(f'{_fileName} exists')                    
                else:
                    # Instantiate a new BlobClient            
                    blob_client = container_client.get_blob_client(_fileName)
                    # upload data
                    blob_client.upload_blob(_file, blob_type="BlockBlob")
    

    use it like This:

    upload(YourDataFrame.to_csv(index=False, encoding = "utf-8"),_connectionString,_containerName,_fileName)