python:转换损坏的xls文件

Jer*_*ril 2 python excel xlrd pandas

我从 SAP 应用程序下载了一些销售数据集。SAP 已自动将数据转换为 .XLS 文件。每当我使用库打开它时,Pandas都会收到以下错误:

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '\xff\xfe\r\x00\n\x00\r\x00'
Run Code Online (Sandbox Code Playgroud)

当我使用 MSEXCEL 打开 .XLS 文件时,它会显示一个弹出窗口,表明当file is corrupt or unsupported extension do you want to continue我单击“是”时,它会显示正确的数据。当我使用 msexcel 将文件再次保存为 .xls 时,我可以使用 .xls 来使用它Pandas

因此,我尝试使用重命名该文件,os.rename()但它不起作用。我尝试打开文件并删除\xff\xfe\r\x00\n\x00\r\x00,但它也不起作用。

解决方案是打开 MSEXCEL 并手动将文件再次保存为 .xls,有什么方法可以自动执行此操作。请帮忙。

Jer*_*ril 5

最后我将损坏的文件转换.xls为正确的.xls文件。以下是代码:

# Changing the data types of all strings in the module at once
from __future__ import unicode_literals
# Used to save the file as excel workbook
# Need to install this library
from xlwt import Workbook
# Used to open to corrupt excel file
import io

filename = r'SALEJAN17.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')

import pandas as pd
df = pd.ExcelFile('myexcel.xls').parse('Sheet1')
Run Code Online (Sandbox Code Playgroud)

没有错误。