2016-11-19 100 views
0

我想從.xlsx文件讀取幾行並將信息保存到列表中。我想要的數據是sheet1這是唯一的表格。下面的代碼似乎打開文件好,並計算有6列。這是對的。嘗試讀取Excel文件中的行

但是,當我嘗試讓python讀取第一行中的數據時,這裏是我得到的:[0,0,0,0,0,0]。我不確定我做錯了什麼。

最終我想要代碼讀取文件的第一行和最後10行。我也包括的片斷由.xlsx文件,所以你可以看到設置有:

enter image description here

蟒蛇的版本我是2.7.12。

from win32com.client import Dispatch 
import string 

scrExcelFile = r"D:/python_class/Semester_Project/index2.xlsx" 
exclApp = Dispatch("Excel.Application") 
exclWrkBk = exclApp.Workbooks.open(scrExcelFile) 
exclsheet = exclWrkBk.Sheets(1) 

lastCol = exclsheet.UsedRange.Columns.Count 
print "The last comlumn number is %r" % lastCol 

headers = [] 
for row in range(1): 
    for col in range(lastCol): 
     headers.append(row) 
print headers 
+1

當您使用範圍(1)時,您正在讀取第0行。可能是這個問題? – dgorti

+1

另外,你一遍又一遍地將'row'附加到'headers',而不是從表格中獲取實際值,然後附加它。 – fotNelton

+0

我嘗試了一些不同的範圍值。當我嘗試範圍0時,出現錯誤,當我嘗試範圍2時,我得到[0,0,0,0,0,0,1,1,1,1,1,1] ..... for some理由它不讀取單元格中的內容 –

回答

0

你沒有采取範圍從0開始巨蟒,並在Excel行的賬戶,列從1開始。所以,你的代碼應該是這樣的:

from win32com.client import Dispatch 
import string 

scrExcelFile = r"D:111.xlsx" 
exclApp = Dispatch("Excel.Application") 
exclWrkBk = exclApp.Workbooks.open(scrExcelFile) 
exclsheet = exclWrkBk.Sheets(1) 

lastCol = exclsheet.UsedRange.Columns.Count 
print ("The last comlumn number is %r" % lastCol) 

headers=[] 
for r in range(1,lastCol+1): 
    headers.append(exclsheet.Cells(1,r).Value) 
print (headers) 

除了這個請檢查以下問題以提高性能:Excel using win32com and python

+0

當我輸入你的代碼來嘗試它時,我得到了[1,1,1,1,1,1]有些東西仍然不正確 –

+1

@kristen,我更新了我的代碼 – bzimor

+0

更新了代碼主要工作,它沒有得到最後一列,但它不是0的列表了!非常感謝!我在列表中的每個元素前面都有一個'u'。我以前沒有見過,這是什麼意思? –