我知道有一些类似的问题,尽管它们都没有帮助我解决我的问题。最终目标是拥有一个 Flask 应用程序,它接受一个 excel 文件,将其存储在 azure blob 存储中,然后由我的 python 函数应用程序使用它来进行一些进一步的转换。我所困扰的是如何编码/解码这个文件,因为我必须使用
block_blob_service.create_blob_from_bytes()
函数。
我唯一想到的是使用 Pandas 库来读取这个 excel,然后使用 tobytes()
函数。这样,我就可以将 excel 作为 CSV 文件上传到 blob。但是我无法真正将其转换为以前的形式。
这是打开后的样子:
9]�0�j�9p/�j�� �`��/wj1=p/�j�� p�^�.wj2=p/�[...]
尝试使用 utf-8 对其进行解码会出现一些永无休止的错误,表示“utf-8”编解码器无法解码字节[...] 我尝试了许多不同的编码,但它总是以此消息结束一些字节。 Excel 包含数字、字符串和日期。
所以,到代码:
#getting the file
file = request.files['file']
#reading into pandas df
data = pd.read_excel(file)
df_to_records = data.to_records(index=False)
records_to_bytes = df_to_records.tobytes()
block_blob_service = BlockBlobService(account_name='xxx', account_key="xxx")
block_blob_service.create_blob_from_bytes("test","mydata.csv",records_to_bytes)
感谢您的建议!
最佳答案
更新:在我这边工作的完整代码。
import os
from flask import Flask, request, redirect, url_for
from azure.storage.blob import BlockBlobService
import string, random, requests
app = Flask(__name__, instance_relative_config=True)
account = "your_account name" # Azure account name
key = "account key" # Azure Storage account access key
container = "f22" # Container name
blob_service = BlockBlobService(account_name=account, account_key=key)
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
file.seek(0)
filename = "test1.csv" # just use a hardcoded filename for test
blob_service.create_blob_from_stream(container, filename, file)
ref = 'http://'+ account + '.blob.core.windows.net/' + container + '/' + filename
return '''
<!doctype html>
<title>File Link</title>
<h1>Uploaded File Link</h1>
<p>''' + ref + '''</p>
<img src="'''+ ref +'''">
'''
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
if __name__ == '__main__':
app.run(debug=True)
运行后:
选择 .csv 文件并单击上传按钮后,在 Azure 门户中检查 .csv 文件:
<小时/>我认为您可以尝试使用方法 create_blob_from_stream
而不是 create_blob_from_bytes
。
这里是示例代码:
def upload_file():
if request.method == 'POST':
file = request.files['file']
file.seek(0)
try:
blob_service = BlockBlobService(account_name='xxx', account_key="xxx")
blob_service.create_blob_from_stream(container, filename, file)
except Exception:
print 'Exception=' + Exception
pass
关于python - 如何使用Python正确编码/解码Excel文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260834/