[英]Issue with reading file encoding within python-Dash-base64
我在 python 3 中使用了一個破折號程序,其中我有一個 dcc.upload 元素,試圖在破折號中上傳文件。 我的代碼如下所示:
upload = html.Div([html.Label('Upload file'),
dcc.Upload(
id='upload-templ',
children=html.Div(['Drag and Drop or ',html.A('Select Files')]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=True
),
html.Div(id='data-upload')])
def parse_contents(contents, filename, date):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'xlsx' in filename:
# Assume that the user uploaded a CSV file
wb = openpyxl.load_workbook(io.StringIO(decoded.decode('utf8')))
ws = wb["sheet"]
all_rows = list(ws.rows)
return html.Div([
'its excell'
])
elif 'temp' in filename:
pptFilepath = io.StringIO(decoded.decode('utf8'))
return html.Div([
'its powerpoint'
])
# Assume that the user uploaded an excel file
#df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
在上傳 PowerPoint 或 excel 文件時,我有以下錯誤:
Powerpoint: 'utf-8' codec can't decode byte 0xca in position 15: invalid continuation byte
Excel: 'utf-8' codec can't decode byte 0xb2 in position 14: invalid start byte
我知道它與我上傳的文件有關。 我該如何解決這個錯誤?
使用BytesIO
而不是StringIO
。
例如改變這一行
wb = openpyxl.load_workbook(io.StringIO(decoded.decode('utf8')))
對此:
wb = openpyxl.load_workbook(io.BytesIO(decoded))
請參閱文檔中的Upload
組件示例以供參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.