python xlrd - 从工作表中检索列索引

时间:2012-07-28 03:35:50

标签: python xlrd

嗨,我只是拿起xlrd。关于访问工作表和单元格属性,我指的是Xlrd Column

那里的代码显示。

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 个答案:

答案 0 :(得分:1)

您在阅读或撰写Excel文件吗? xlrd用于读取excel文件,xlwt用于写入

我相信你错过了

之间的中间步骤
           inBook = xlrd.open_workbook('T:/AzReporting/DraftUtilization.xls')

           for crange in outBook.col_label_ranges:

您必须指定Excel文件的工作表

即使该示例也标有“thesheet”

我想改变

           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/