簡體   English   中英

使用Python讀取XLS文件時出現錯誤(little-endian)

[英]Error (little-endian) reading a XLS file with python

我使用硒從網上下載了XLS文件。

我嘗試了在堆棧溢出和其他網站中找到的許多選項來讀取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評論啟發的解決方案。

## 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

謝謝你們!

pd是什么意思? 什么

熊貓是為數據科學而設計的。 在我看來,您必須使用openpyxl (僅讀取和寫入xlsx)或xlwt / xlrd (讀取xls ...並僅寫入xls)。

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

它在互聯網上有幾個例子...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM