使用python从BytesIO创建excel文件
我正在使用使用python从BytesIO创建excel文件,python,pandas,xlsxwriter,bytesio,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) wri
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文件并将其存储在本地。我该怎么做?最后,我得到了解决方案。以下是执行的步骤:
#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")
你有具体的问题吗?您已经试过什么了?通过我上面的代码,我可以在控制台中看到bytesIO数据。但我不知道如何将它写入excel文件好吧,但你说你在数据库中得到了它,对吗?是的,在数据库中,文件是varbinary格式的。现在,我正在尝试将varbinary数据导出回excel,以确保我的代码正常工作。我不熟悉BytesIO,您能解释一下它的用途吗?您可能不需要使用BytesIO和Pandas的最后步骤。您可以使用类似于
的open('outputFile.xlsx',wb')将查询结果写入xlsxfile:xlsxfile.write(result[0][0])
.Ohk。我想利用pandas
生成文件,因此使用了它。但方向是好的。