【问题标题】:Python - XLRDError: Unsupported format, or corrupt file: Expected BOF recordPython - XLRDError:不支持的格式,或损坏的文件:预期的 BOF 记录
【发布时间】:2019-08-16 18:28:30
【问题描述】:

我正在尝试打开一个为我的项目提供给我的 excel 文件,该 excel 文件是我们从 SAP 系统获得的文件。但是当我尝试使用 pandas 打开它时,我收到以下错误:

XLRDError:不支持的格式,或损坏的文件:预期的 BOF 记录;找到 '\xff\xfe\r\x00\n\x00\r\x00'

以下是我的代码:

import pandas as pd
# To open an excel file
df = pd.ExcelFile('myexcel.xls').parse('Sheet1')

【问题讨论】:

  • 你能在msexcel中打开文件吗?
  • 是的,我可以使用 msexcel 打开它,但不能在 pandas 中打开
  • 能否附上问题中的XLS文件?
  • 嗨,Arpit,实际上数据有点机密,都是医疗数据。

标签: python pandas xlrd


【解决方案1】:

不知道它对我有用后是否对你有用,但无论如何你可以尝试以下方法:

from __future__ import unicode_literals
from xlwt import Workbook
import io

filename = r'myexcel.xls'
# Opening the file using 'utf-16' encoding
file1 = io.open(filename, "r", encoding="utf-16")
data = file1.readlines()

# Creating a workbook object
xldoc = Workbook()
# Adding a sheet to the workbook object
sheet = xldoc.add_sheet("Sheet1", cell_overwrite_ok=True)
# Iterating and saving the data to sheet
for i, row in enumerate(data):
    # Two things are done here
    # Removeing the '\n' which comes while reading the file using io.open
    # Getting the values after splitting using '\t'
    for j, val in enumerate(row.replace('\n', '').split('\t')):
        sheet.write(i, j, val)

# Saving the file as an excel file
xldoc.save('myexcel.xls')

【讨论】:

  • 嗨,我收到以下错误Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'xlwt'
  • 你需要安装xlwt库。
  • 你可以试试encoding='utf-16le'
  • 对于某些文件,它使用utf-16le,而对于其他文件,它使用utf-16。无论如何感谢您的回答。
【解决方案2】:

我遇到了同样的xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; 错误,并通过编写 XML 到 XLSX 转换器解决了它。您可以在转换后致电pd.ExcelFile('myexcel.xlsx')。原因是实际上,pandas 使用 xlrd 来读取 Excel 文件,而 xlrd 不支持 XML 电子表格 (*.xml),即不支持 XLS 或 XLSX 格式。

import pandas as pd
from bs4 import BeautifulSoup

def convert_to_xlsx():
    with open('sample.xls') as xml_file:
        soup = BeautifulSoup(xml_file.read(), 'xml')
        writer = pd.ExcelWriter('sample.xlsx')
        for sheet in soup.findAll('Worksheet'):
            sheet_as_list = []
            for row in sheet.findAll('Row'):
                sheet_as_list.append([cell.Data.text if cell.Data else '' for cell in row.findAll('Cell')])
            pd.DataFrame(sheet_as_list).to_excel(writer, sheet_name=sheet.attrs['ss:Name'], index=False, header=False)

        writer.save()

【讨论】:

    【解决方案3】:

    对我有用的是应用这个建议:

    How to cope with an XLRDError

    在那里,您还可以找到适合我的合适解释。它说问题是文件格式未正确保存。当我打开 xls 文件时,它提出将其另存为 html。我将其保存为“.xlsx”并解决了问题

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2013-05-06
      • 2014-07-22
      • 2019-01-28
      • 2021-11-30
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 2013-12-24
      相关资源
      最近更新 更多