Azure Function - Pandas dataframe to Excel, write to outputBlob stream

送分小仙女□ 提交于 2021-02-11 12:32:35

问题


Am trying to write a DataFrame to an outputBlob from an Azure Function. I'm having trouble figuring out which io stream to use.

My function looks like this:

    import io
    import xlrd
    import pandas as pd

    def main(myblob: func.InputStream, outputBlob: func.Out[func.InputStream]):
        logging.info(f"Python blob trigger function processed blob \n"
                     f"Name: {myblob.name}\n"
                     f"Blob Size: {myblob.length} bytes")
    
        input_file = xlrd.open_workbook(file_contents = myblob.read())
        df = pd.read_excel(input_file)
        if not df.empty:
            output = io.BytesIO()
            outputBlob.set(runway1.to_excel(output))

How do we save the DataFrame to a stream that is recognisable by the Azure Function to write the excel to a Storage Container?


回答1:


If you want to save DataFrame as excel to Azure blob storage, please refer to the following example

  1. SDK
azure-functions==1.3.0
numpy==1.19.0
pandas==1.0.5
python-dateutil==2.8.1
pytz==2020.1
six==1.15.0
xlrd==1.2.0
XlsxWriter==1.2.9
  1. Code
import logging
import io
import xlrd
import pandas as pd
import xlsxwriter 
import azure.functions as func


async def main(myblob: func.InputStream,outputblob: func.Out[func.InputStream]):
    
    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {myblob.name}\n")
    input_file = xlrd.open_workbook(file_contents = myblob.read())
    df = pd.read_excel(input_file)
    if not df.empty:
            xlb=io.BytesIO()
            writer = pd.ExcelWriter(xlb, engine= 'xlsxwriter')
            df.to_excel(writer,index=False)
            writer.save()
            xlb.seek(0) 
            outputblob.set(xlb)
            logging.info("OK")



来源:https://stackoverflow.com/questions/62772719/azure-function-pandas-dataframe-to-excel-write-to-outputblob-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!