2015-11-03 58 views
-5

我有一個有4行5列的excel表。最後一列有兩個值中的任何一個,即。完成並等待。我想要的是將其最後一列值爲行的行導出爲文本文件。我已經嘗試了代碼,但它給錯誤預計會出現縮進塊錯誤

import xlrd 

workbook=xlrd.open_workbook('C:/Users/admin/Documents/omkar.xlsx') 
sh=workbook.sheet_by_name('Sheet1') 

def ncols(): 

print sh.nrows 
print sh.ncols 

n=0 
i=0 

file=open('C:/Users/admin/Documents/om.txt','w') 

for n in range(sh.nrows): 

    for i in range(sh.ncols): 
     data =str(sh.cell_value(n,i)) + " " 

    if sh.cell_value(n,ncols) == "pending": 

     print data, 
     file.write(data + " ") 

    print 
    file.write("\n") 
+0

也許你應該嘗試另一種代碼? – Julien

+1

顯示您的代碼。顯示你的預期。顯示你所得到的。 –

+0

使用[Excel自動篩選器](https://support.office.com/en-gb/article/Filter-data-in-an-Excel-table-7d8e9739-2898-4bfe-9d0f-c6204e6e5c8a)並複製/粘貼排隊。 – TessellatingHeckler

回答

0
import xlrd 

workbook=xlrd.open_workbook('C:/Users/admin/Documents/omkar.xlsx') 
sh=workbook.sheet_by_name('Sheet1') 

def ncols(): 

print sh.nrows 
print sh.ncols 

n=0 
i=0 

file=open('C:/Users/admin/Documents/om.txt','w') 

for n in range(sh.nrows): 

    for i in range(sh.ncols): 
     data =str(sh.cell_value(n,i)) + " " 

    if sh.cell_value(n,ncols) == "pending": 

     print data, 
     file.write(data + " ") 

    print 
    file.write("\n") 

應該是─

import xlrd 

workbook=xlrd.open_workbook('C:/Users/admin/Documents/omkar.xlsx') 
sh=workbook.sheet_by_name('Sheet1') 

def ncols(): 
    print sh.nrows 
    print sh.ncols 

    file = open('C:/Users/admin/Documents/om.txt', 'w') 

    for n in range(sh.nrows): 
     if sh.cell_value(n, sh.ncols-1) == 'pending': 
      for i in range(sh.ncols): 
       data = str(sh.cell_value(n, i)) + ' ' 
       print data, 
       file.write(data) 
      print 
      file.write('\n') 

ncols() 
+0

對不起,但它既沒有給出任何輸出也沒有創建任何文本文件 – user3544059

+0

所以也沒有顯示錯誤CrakC – user3544059

+0

@ user3544059這是因爲你的方法是錯誤的。同樣當你定義一個函數時,你也需要調用它。檢查我更新的答案。這應該可以解決你的問題。 – CrakC