【问题标题】:Error (little-endian) reading a XLS file with python使用 python 读取 XLS 文件时出错(小端序)
【发布时间】:2018-08-18 06:19:12
【问题描述】:

我使用 selenium 从网上下载了一个 XLS 文件。

我尝试了许多在 stack-overflow 和其他网站上找到的选项来读取 XLS 文件:

import pandas as pd
df = pd.read_excel('test.xls') # Read XLS file
Expected "little-endian" marker, found b'\xff\xfe'

和

df = pd.ExcelFile('test.xls').parse('Sheet1') # Read XLSX file
Expected "little-endian" marker, found b'\xff\xfe'

再来一次

from xlrd import open_workbook
book = open_workbook('test.xls') 
CompDocError: Expected "little-endian" marker, found b'\xff\xfe'

我尝试了不同的编码:utf-8、ANSII、utf_16_be、utf16 我什至尝试从记事本或其他应用程序中获取文件的编码。

文件类型:Microsoft Excel 97-2003 工作表 (.xls) 我可以用 Excel 打开文件,没有任何问题。 令人沮丧的是,如果我用 excel 打开文件然后按保存,我就可以用前面的 python 命令读取文件。

如果有人能提供我可以尝试的其他想法,我将不胜感激。我只需要用 python 脚本打开这个文件。

谢谢, 最大

解决方案(有点混乱但简单)可能适用于任何类型的 Excel 文件:

从 python 调用 VBA 以打开并将文件保存在 Excel 中。 Excel“清理”文件,然后 Python 可以使用任何读取 Excel 类型的函数来读取它

受@Serge Ballesta 和@John Y cmets 启发的解决方案。

## Open a file in Excel and save it to correct the encoding error 
import win32com.client
import pandas

downloadpath="c:\\firefox_downloads\\"
filename="myfile.xls"

xl=win32com.client.Dispatch("Excel.Application")
xl.Application.DisplayAlerts = False # disables Excel pop up message (for saving the file)
wb = xl.Workbooks.Open(Filename=downloadpath+filename)
wb.SaveAs(downloadpath+filename)
wb.Close
xl.Application.DisplayAlerts = True  # enables Excel pop up message for saving the file

df = pandas.ExcelFile(downloadpath+filename).parse('Sheet1') # Read XLSX file

谢谢大家!

【问题讨论】:

  • 您下载的文件可能不是 XLS 格式,也不是 UTF-8 CSV 格式。但是仍然有很多可能的格式,如果不了解该文件的更多信息,我真的无法猜测......
  • 我可以用 Excel 打开文件没有问题。当我下载它时,它有一个 .xls 扩展名。文件类型:Microsoft Excel 97-2003 工作表 (.xls) 我从访问 MySQL 数据库下载文件以生成此 Excel 文件的网站。我认为他们用来执行此操作的源代码是 C# 它有大约 10 列 80 行。我可以尝试发送样品
  • Excel 可以检测和加载多种格式。当您打开原始文件然后将其保存回来时,您是否有关于更改格式的消息?
  • 当我保存或另存为或另存为 .xlsx 文件时没有任何消息。它只是保存它,然后我可以使用例如 pandas.read_excel 打开它
  • 正如我已经说过的,没有文件示例(不是它的内容),我无法猜测格式...

标签: python excel pandas dataframe encoding


【解决方案1】:

pd 是什么意思?什么

pandas 专为数据科学而生。在我看来,你必须使用 openpyxl(只读写 xlsx)或 xlwt/xlrd(读取 xls... 并且只写 xls)。

from xlrd import open_workbook
book = open_workbook(<math file>)
sheet =.... 

在网上有几个这样的例子……

【讨论】:

  • 感谢您的回复。我试过这个已经想到了: from xlrd import open_workbook book = open_workbook('test.xls') CompDocError: Expected "little-endian" marker, found b'\xff\xfe'
  • CompDocError 表示您的文件已损坏或类似情况。也许首先检查文件是否可以在 excel 上正确打开。否则,把这个文件贴在这里,我会在我这边试试……
猜你喜欢
  • 2015-05-29
  • 2018-04-27
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
相关资源
最近更新 更多