2016-05-25 78 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)