python:转换损坏的 xls 文件

问题描述 投票:0回答:3

我从 SAP 应用程序下载了一些销售数据集。 SAP 已自动将数据转换为 .XLS 文件。每当我使用

Pandas
库打开它时,我都会收到以下错误:

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '\xff\xfe\r\x00\n\x00\r\x00'

当我使用 MSEXCEL 打开 .XLS 文件时,它会显示一个弹出窗口,指出当我单击“是”时,

file is corrupt or unsupported extension do you want to continue
显示了正确的数据。当我使用 msexcel 将文件再次保存为 .xls 时,我可以使用
Pandas
.

使用它

所以,我尝试使用

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

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

python excel pandas xlrd
3个回答
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')

没有错误。


2
投票

解决此问题的另一种方法是使用 win32com.client 库:

import win32com.client
import os

o = win32com.client.Dispatch("Excel.Application")
o.Visible = False

filename = os.getcwd() + '/' + 'SALEJAN17.xls'
output = os.getcwd() + '/' + 'myexcel.xlsx'

wb = o.Workbooks.Open(filename)
wb.ActiveSheet.SaveAs(output,51)

在我的示例中,您保存为 .xlsx 格式,但也可以另存为 .xls。


0
投票

按照@Jeril的回答,我们可以跳过保存文件过程并将其直接加载到pandas。

将 pandas 导入为 pd 导入io

file_path = '数据/some_file.xls'

加载utf-16编码的文件

使用 io.open(file_path, "r",encoding="utf-16") 作为 file1: 数据 = file1.readlines()

按选项卡拆分值并创建 DataFrame

data_list = [row.replace(' ', '').split(' ') 对于数据中的行] max_list = max(len(row) for data_list 中的行) data_list_clean = [data_list 中的行,如果 len(row) == max_list]

提取列名称(data_list 中的第一个列表)

列名称 = data_list_clean[0]

使用剩余的行和列名称创建一个 DataFrame

df = pd.DataFrame(data_list_clean[1:], columns=column_names) 显示(df)

© www.soinside.com 2019 - 2024. All rights reserved.