hand_excel
来源:互联网 发布:淘宝店铺动态怎么看 编辑:程序博客网 时间:2024/06/10 20:23
</pre>简单的读写 excel 用例<pre name="code" class="python">#!/usr/bin/env python# -*- coding: utf-8 -*-# @Date : 2014-04-10 21:47:56# @Function: 指定选取三列然后挑选出同时满足>=1或者同时<=-1的 将其所有数据存入新的csv表格中 # @Author : BeginManimport osimport stringimport xlrdimport xlwtdef get_data(): """获取excel数据源""" #file = r'C:\Users\Administrator\Desktop\pytool\xlrd\initial_log_data.xls' file = '/home/Svn_podm/zengjj/file.xlsx' # 改成自己的路径 filepath = raw_input('please input the file name:') is_valid = False # 验证文件 try: filepath = [file, filepath][filepath != ''] print filepath # 判断给出的路径是不是xls格式 if os.path.isfile(filepath): filename = os.path.basename(filepath) if filename.split('.')[1] == 'xlsx': is_valid = True data = None if is_valid: data = xlrd.open_workbook(filepath) except Exception, e: print 'operation failed %s' %e return None return datadef handle_data(): """处理数据""" data = get_data() if data: col_format = ['B', 'C', 'D'] # 指定的列 inp = raw_input('please input the choice three colume ,division by , : ') try: inp = inp.split(',') col_format = [col_format,inp][len([i for i in inp if i in string.letters]) == 3] col_format = [i.upper() for i in col_format] # 转换成大写 table = data.sheet_by_index(0) # 选取第一个工作区 nrows = table.nrows # 行数 ncols = table.ncols # 列数 str_upcase = [i for i in string.uppercase] # 所有大写字母 i_upcase = range(len(str_upcase)) # 对应的数字 ncols_dir = dict(zip(str_upcase,i_upcase)) # 格式成字典 col_index = [ncols_dir.get(i) for i in col_format] # 获取指定列所对应的索引 # 选取的三列是否同时满足 >=1或者同时<=-1 print 'checking:\n' count = 0 result = [] for i in xrange(nrows): cell_0 = table.cell(i,col_index[0]).value cell_1 = table.cell(i,col_index[1]).value cell_2 = table.cell(i,col_index[2]).value if (cell_0>=1 and cell_1>=1 and cell_2>=1) or (cell_0<=-1 and cell_1<=-1 and cell_2<=-1): result.append(table.row_values(i)) # 将符合要求的一行添加进去 count += 1 print 'all rows %s cols %s satify %s' %(nrows, ncols, count) print 'write data' col_name = col_format[0]+col_format[1]+col_format[2] if write_data(result, col_name): print 'write success' except Exception, e: print 'operation failed %s' %e return None else: print 'operation failed' return Nonedef write_data(data, name): """写入数据,data为符合条件的数据列表,name表示指定的哪三个列,以此命名""" file = xlwt.Workbook() table = file.add_sheet(name,cell_overwrite_ok=True) l = 0 # 表示行 for line in data: c = 0 # 表示一行下的列数 for col in line: table.write(l,c,line[c]) c += 1 l += 1 defatul_f = os.getcwd() # 默认路径 f = raw_input('choice the file to save:') f_name = '/%s.xls' % name filepath = [defatul_f+f_name, f+f_name][f != ''] file.save(filepath) return Truedef main(): handle_data()if __name__ == '__main__': main()
0 0