python - 使用 python 从 BytesIO 创建一个 excel 文件
问题描述
我正在使用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 文件。
蟒蛇代码:
#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")
推荐阅读
- java - Android Studio onClick 显示方法根本不起作用
- python - 如何在 Django 上自动运行我自己的 .py
- scheme - make-counter 保留下一个变量的状态
- python - 如何在 tkinter 中打印随机文本?
- c# - 应用程序在“Process.Start”之后在后台运行。如何解决这个问题?
- html - 如何在不偏移固定导航栏的情况下跳转到链接?
- django - Pipenv 无法在远程服务器上安装 boto3 (Heroku)
- r - dplyr 在变量的子集上使用 pivot_longer 和 pivot_wider
- php - phpseclib 绝对路径上传
- javascript - 如何在我的应用程序中提供用户对用户的付款?