2016-05-25 77 views
2

我有一张xlsx文件。 我想用python 3(xlrd lib)打开它,但是我得到一个空文件!如何用python 3打开xlsx文件

我用这个代码:

file_errors_location = "C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx" 
workbook_errors = xlrd.open_workbook(file_errors_location) 

,我没有错误,但是当我键入:

workbook_errors.nsheets 

我得到“0”,即使该文件具有一定的床单......当I型:

workbook_errors 

我得到:

xlrd.book.Book object at 0x2.. 

有帮助吗?感谢

+0

当你调用 'workbook_errors.sheets()',然后 'workbook_errors.nsheets' 会发生什么? –

回答

1

有两个模块读取xls文件:openpyxl和xlrd

这个脚本允许你在Excel中的数据转换成dictionnaries的名单使用xlrd

import xlrd 

workbook = xlrd.open_workbook('C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx') 
workbook = xlrd.open_workbook('C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx', on_demand = True) 
worksheet = workbook.sheet_by_index(0) 
first_row = [] # The row where we stock the name of the column 
for col in range(worksheet.ncols): 
    first_row.append(worksheet.cell_value(0,col)) 
# tronsform the workbook to a list of dictionnary 
data =[] 
for row in range(1, worksheet.nrows): 
    elm = {} 
    for col in range(worksheet.ncols): 
     elm[first_row[col]]=worksheet.cell_value(row,col) 
    data.append(elm) 
print data 
+0

当我输入:“worksheet = workbook.sheet_by_index(0)” 我得到的错误:“列表索引超出范围....” 因为如果我键入工作表.nsheets,我得到0! –

+0

然后你的文件是空的! –

+0

不...我现在试着打开一个新的文件,它运行良好..它似乎文件被锁定或somthing –

0

您可以使用熊猫pandas.read_excel就像pandas.read_csv

import pandas as pd 
file_errors_location = 'C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx' 
df = pd.read_excel(file_errors_location) 
print(df)