那如果上面的代码我想它同时支持xls和xlsx两种格式该如何修改
时间: 2023-11-22 14:56:32 浏览: 38
要支持 `.xls` 和 `.xlsx` 两种格式,你可以将 `pandas` 的 `read_excel` 方法替换为 `read_excel_io` 方法。这个方法可以接受一个 `BytesIO` 对象,因此你可以将文件内容读入内存,然后再将其转换为 `BytesIO` 对象传递给 `read_excel_io` 方法。
以下是修改后的代码:
```python
import pandas as pd
from io import BytesIO
def read_excel(file):
# 读取文件内容
content = file.read()
# 将文件内容转换为 BytesIO 对象
file = BytesIO(content)
# 判断文件类型
if file.name.endswith('.xls'):
# 读取 .xls 文件
df = pd.read_excel_io(file, engine='xlrd')
elif file.name.endswith('.xlsx'):
# 读取 .xlsx 文件
df = pd.read_excel_io(file, engine='openpyxl')
else:
raise ValueError('Unsupported file type')
# 返回 DataFrame
return df
```
注意,这里使用了 `BytesIO` 对象来读取文件内容,并且需要根据文件扩展名选择不同的 `engine` 参数。