python操作excel

import xlrd
Book=xlrd.open_workbook(r'E:\test_work\NASDAQ全部股票-行情报价(1).xls')#打开指定的Excel文件,返回一个Book对象
#通过Book对象可以得到各个Sheet对象(一个Excel文件可以有多个Sheet,每个Sheet就是一张表格)。

print(Book.nsheets)#返回Sheet的数目。

print(Book.sheets())#返回所有Sheet对象的list。

print(Book.sheet_by_index(0))#返回指定索引处的Sheet。相当于Book.sheets()[index]。获取索引为0的sheet
#
print(Book.sheet_names())#返回所有Sheet对象名字的list。
#
Sheet=Book.sheet_by_name('NASDAQ全部股票-行情报价')#根据指定Sheet对象名字返回Sheet。
#通过Sheet对象可以获取各个单元格,每个单元格是一个Cell对象。

print(Sheet.name)#返回表格的名称。

print(Sheet.nrows)#返回表格的行数。

print(Sheet.ncols)#返回表格的列数。

print(Sheet.row(1))#获取指定行,返回Cell对象的list。获取索引为1的行
#
print(Sheet.row_values(1))#获取指定行的值,返回list。获取索引为1的行的
#
print(Sheet.col(1))#获取指定列,返回Cell对象的list。获取索引为1的列
#
print(Sheet.col_values(1))#获取指定列的值,返回list。获取索引为1的列的值
#
print(Sheet.cell(1, 1))#根据位置获取Cell对象。获取行索引为1列索引也为1的Cell对象

Cell=Sheet.cell(1, 1)#根据位置获取Cell对print(Sheet.cell_value(1, 1))#根据位置获取Cell对象的值。获取行索引为1列索引也为1的Cell对象的值
 print(Cell.value)#返回单元格的值。

 

# 打印每张表的最后一列的值
# 方法1
for s in wb.sheets():
    print("== The last column of sheet '%s' ==" % (s.name))
    for i in range(s.nrows):
        print(s.row(i)[-1].value)

# 方法2
for i in range(wb.nsheets):
    s = wb.sheet_by_index(i)
    print("== The last column of sheet '%s' ==" % (s.name))
    for v in s.col_values(s.ncols - 1):
        print(v)

# 方法3
for name in wb.sheet_names():
    print("== The last column of sheet '%s' ==" % (name))
    s = wb.sheet_by_name(name)
    c = s.ncols - 1
    for r in range(s.nrows):
        print(s.cell_value(r, c))

 

posted @ 2018-05-21 15:17  Operater  阅读(337)  评论(0编辑  收藏  举报