gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:20:48 29 4
gpt4 key购买 nike

我正在使用 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/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com