2012-07-28 51 views
1

嗨,我只是拿起xlrd。關於訪問表和單元格屬性,我指Xlrd Columnpython xlrd - 從工作表檢索列索引

從那裏的代碼顯示。

for crange in thesheet.col_label_ranges: 
    rlo, rhi, clo, chi = crange 
    for rx in xrange(rlo, rhi): 
     for cx in xrange(clo, chi): 
      print "Column label at (rowx=%d, colx=%d) is %r" \ 
       (rx, cx, thesheet.cell_value(rx, cx)) 

所以我以爲我只是測試從表單「數據」打印出單元格A1,所以我開始複製上面的例子。

在col_label_ranges當它完成但它的錯誤:

inBook = xlrd.open_workbook('T:/AzReporting/DraftUtilization.xls') 
outBook = xlutils.copy.copy(inBook) 
for crange in outBook.col_label_ranges: 
    rlo, rhi, clo, chi = crange 
    for rx in xrange(rlo, rhi): 
     for cx in xrange(clo, chi): 
      print "Column label at (rowx=%d, colx=%d) is %r" \ 
      (rx, cx, outBook.cell_value(0, 0)) 

Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
AttributeError: 'Workbook' object has no attribute 'col_label_ranges' 

另外,如果我改變col_label_names是工作表的名稱也錯誤。我會用這個例子遺漏一些東西。也許有更好的教程可以遵循?

for crange in outBook.Data: 

回答

1

你正在閱讀或寫作excel文件嗎? xlrd被讀取Excel文件和xlwt是編寫

我相信你缺少

  inBook = xlrd.open_workbook('T:/AzReporting/DraftUtilization.xls') 

  for crange in outBook.col_label_ranges: 

之間的中間步驟中,您必須指定Excel中的表文件

即使這個例子被標記爲「thesheet」

我的gues更迭

  for crange in outBook.col_label_ranges: 

  sh=inBook.sheet_by_index(0) 
      for crange in sh.col_label_ranges: 

http://www.numbergrinder.com/2008/10/pulling-data-from-excel-using-python-xlrd/