2016-08-08 154 views
1

我想從XLSX文件讀取第二列和第三列中給出的數據。如何使用python腳本讀取XLSX文件的特定列中的數據

import xlrd 

workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") 
sheet = workbook.sheet_by_index(0) 
for row in range(sheet.nrows): 
    cols = (sheet.row_values(row,1)) and (sheet.row_values(row,2)) 
    print(cols) 

不過是給下面的錯誤,當我上面的腳本執行..

biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File 
C:\Python27\.....\xlrd_init_.py", line 1323, in getbof raise 
XLRDError('Expected BOF record; found 0x%04x' % opcode) 
xlrd.biffh.XLRDError: Expected BOF record; found 0x4b50 
+0

biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) 文件「C:\ Python27 \ ..... \ xlrd \ __ init__.py」,第1323行,在getbof中 引發XLRDError('Expected BOF record;發現0x%04x'%操作碼) xlrd.biffh.XLRDError:期望的BOF記錄;找到0x4b50 – Pkde

+0

[在python中打開和閱讀excel .xlsx文件]可能的重複(http://stackoverflow.com/questions/18532893/opening-and-reading-an-excel-xlsx-file-in-python) –

回答

0

試試這個

import xlrd 

workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") 
sheets = workbook.sheet_names() 
required_data = [] 
for sheet_name in sheets: 
    sh = workbook.sheet_by_name(sheet_name) 
    for rownum in range(sh.nrows): 
     row_valaues = sh.row_values(rownum) 
     required_data.append((row_valaues[0], row_valaues[1])) 
print required_data 
0

這個例子讀取Excel工作表的所有內容,並把它放在一個矩陣(名單列表),那麼你可以使用的列,您需要:

import xlrd 

workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") 
sheet = workbook.sheet_by_index(0) 
rows = [] 
for i in range(sheet.nrows): 
    columns = [] 
    for j in range(sheet.ncols): 
     columns.append(sheet.cell(i, j).value) 
    rows.append(columns) 
print rows 
相關問題