python 处理 excel格式文件

时间:2022-11-05 14:35:19

python 调用xlrd package就可以处理excel文件. 简单例子如下:


源码如下:

# -*- coding: utf-8 -*-

import xlrd


 
#----------------------------------------------------------------------
def open_file(path):
    """
    Open and read an Excel file
    """
    book = xlrd.open_workbook(path)
 
    ncols = 0
    nrows = 0
    for n, s in enumerate(book.sheets()):           
        #print "Sheet %d is called %s and has %d columns and %d rows" % (n, s.name, s.ncols, s.nrows)
        nrows = s.nrows
        ncols = s.ncols
    print "rows length is: " + str(nrows) + "\n"
     
    print "columns length is: " + str(ncols) + "\n"
    
    part_name2 = ""
    part_name1 = ""
    file_flag = 0
    first_sheet = book.sheet_by_index(0)
    for n in xrange(0, nrows):
       
        cells = first_sheet.row_slice(rowx=n,
                                start_colx=0,
                                end_colx=4)
        


        for cell in cells:
          print cell.value
#----------------------------------------------------------------------
if __name__ == "__main__":
    path = "file_score.xls"
    open_file(path)