Python对Excel的读写主要有xlrd、xlwt、xlutils、openpyxl、xlsxwriter几种。
1.xlrd主要是用来读取excel文件
1 2 3 4 5 6 7 8 |
import xlrd data = xlrd.open_workbook( 'abcd.xls' ) # 打开xls文件 table = data.sheets()[ 0 ] # 打开第一张表 nrows = table.nrows # 获取表的行数 for i in range (nrows): # 循环逐行打印 if i = = 0 : # 跳过第一行 continue print (table.row_values(i)[: 13 ]) # 取前十三列 |
示例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#coding=utf-8 ####################################################### #filename:test_xlrd.py #author:defias #date:xxxx-xx-xx #function:读excel文件中的数据 ####################################################### import xlrd #打开一个workbook workbook = xlrd.open_workbook( 'E:\\Code\\Python\\testdata.xls' ) #抓取所有sheet页的名称 worksheets = workbook.sheet_names() print ( 'worksheets is %s' % worksheets) #定位到sheet1 worksheet1 = workbook.sheet_by_name(u 'Sheet1' ) """ #通过索引顺序获取 worksheet1 = workbook.sheets()[0] #或 worksheet1 = workbook.sheet_by_index(0) """ """ #遍历所有sheet对象 for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) """ #遍历sheet1中所有行row num_rows = worksheet1.nrows for curr_row in range (num_rows): row = worksheet1.row_values(curr_row) print ( 'row%s is %s' %
|