python - 使用python从BytesIO创建一个excel文件

标签 python pandas xlsxwriter bytesio

我正在使用 pandas将 excel 存储到的库 bytesIO内存。后来,我把这个bytesIO存起来对象到 SQL Server 如下 -

    df = pandas.DataFrame(data1, columns=['col1', 'col2', 'col3'])
    output = BytesIO()
    writer = pandas.ExcelWriter(output,engine='xlsxwriter')
    df.to_excel(writer)
    writer.save()
    output.seek(0)
    workbook = output.read()

    #store into table
    Query = '''
            INSERT INTO [TABLE]([file]) VALUES(?)
            '''
    values = (workbook)
    cursor = conn.cursor()
    cursor.execute(Query, values)
    cursor.close()
    conn.commit()

   #Create excel file.
   Query1 = "select [file] from [TABLE] where [id] = 1"
   result = conn.cursor().execute(Query1).fetchall()
   print(result[0])

现在,我想从表中拉回 BytesIO 对象并创建一个 excel 文件并将其存储在本地。我该怎么做?

最佳答案

最后,我得到了解决方案。以下是执行的步骤:

  • 获取 Dataframe 并将其转换为 excel 并以 BytesIO 格式存储在内存中。
  • 将 BytesIO 对象存储在具有 varbinary(max)
  • 的数据库列中
  • 拉取存储的 BytesIO 对象并在本地创建一个 excel 文件。

  • python 代码:
    #Get Required data in DataFrame:
    df = pandas.DataFrame(data1, columns=['col1', 'col2', 'col3'])
    
    #Convert the data frame to Excel and store it in BytesIO object `workbook`:
    output = BytesIO()
    writer = pandas.ExcelWriter(output,engine='xlsxwriter')
    df.to_excel(writer)
    writer.save()
    output.seek(0)
    workbook = output.read()
    
    #store into Database table
    Query = '''
            INSERT INTO [TABLE]([file]) VALUES(?)
            '''
    values = (workbook)
    cursor = conn.cursor()
    cursor.execute(Query, values)
    cursor.close()
    conn.commit()
    
    #Retrieve the BytesIO object from Database
    Query1 = "select [file] from [TABLE] where [id] = 1"
    result = conn.cursor().execute(Query1).fetchall()
    
    WriteObj = BytesIO()
    WriteObj.write(result[0][0])  
    WriteObj.seek(0)  
    df = pandas.read_excel(WriteObj)
    df.to_excel("outputFile.xlsx") 
    

    关于python - 使用python从BytesIO创建一个excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59348309/

    相关文章:

    python - 如何根据时差分离 Pandas 数据框?

    python - 使用 pandas df.query() 过滤分类(间隔)列

    python - xlsxwriter.Workbook 属性错误 : 'module' object has no attribute 'Workbook'

    python - Django 没有名为 backendssocial.apps.django_app.context_processors 的模块

    python - Pyspark,以编程方式初始化 spark : IllegalArgumentException: Missing application resource

    python - 类型错误 : '<=' not supported between instances of 'str' and 'int' Duplicate

    python - 无法使用 os.remove 删除文件夹(WindowsError : [Error 5] Access is denied: 'c:/temp/New Folder' )

    python - Pandas 过滤和组合

    excel - 将 worksheet.hide_gridlines(2) 设置为特定范围的单元格

    用于创建新 Excel 工作簿并填充单元格的 Python 函数