python - 在 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
文档中的组件示例以供参考。