首页 > 解决方案 > 如何使用 Python 正确编码/解码 excel 文件?

问题描述

我知道有一些类似的问题,尽管它们都没有帮助我解决我的问题。最终目标是拥有一个烧瓶应用程序,它需要一个 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)

感谢您的任何建议!

标签: pythonazurebinaryazure-blob-storage

解决方案


更新:在我身边工作的完整代码。

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 文件:

在此处输入图像描述


我认为您可以尝试使用 methodcreate_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

推荐阅读