python提取excel文档内容到新文档

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sumup/article/details/78942493

参考:http://blog.csdn.net/cloudox_/article/details/53812213

import xlrd
import xlwt
import re

#打开文件,如果没打开则打印错误
def open_excel(file):
	try:
		data=xlrd.open_workbook(file)
		return data
	except Exception as e:
		print (str(e))
		
#写入新的excel表	
def write_excel(file='result.xls',list=[]):
	#创建一个工作工作簿
	book=xlwt.Workbook()
	#在上面建立sheet1,名称为enroll
	sheet1=book.add_sheet('enroll')
	
	#从第0行开始讲list中的row写入新的sheet中
	i=0
	#list中的每一行
	for app in list:
		#每一行中的每一列中的元素x
		j=0
		for x in app:
			sheet1.write(i,j,x)
			#列数递增
			j=j+1
		#行数递增
		i=i+1
	#保存文件
	book.save(file)	
		
def excel_table_byindex(file,colnameindex=0,by_index=0):
	#打开文件
	data=open_excel(file)
	#取工作簿上的第一个sheet
	table=data.sheets()[0]
	
	#行数和列数
	nrows=table.nrows
	ncols=table.ncols
	
	#默认第0行的值
	colnames=table.row_values(colnameindex)
	
	#创建list来存每一行的值
	list=[]
	#将第一个标题栏加入到list中
	list.append(table.row_values(0))
	
	#将满足条件的行加入到list中
	for rownum in range(1,nrows):#从标题栏的下一行开始遍历每一个行
		row=table.row_values(rownum)#某一行的数据
		#如果这一行存在的话
		if row:
			#if float(table.cell(rownum,8).value)>390.0:
			#将这一行的第3列值与正则表达式匹配
			if re.match(r'李\s*',table.cell(rownum,2).value):
				#匹配成功,加入list中
				list.append(row)
				
	#写入新的excel表		
	write_excel('result.xls',list)
	return list
	

	
def main():
	tables=excel_table_byindex('pytest.xls')
	#打印每一行
	for row in tables:
		print (row)

		
if __name__ =='__main__':
	main()


猜你喜欢

转载自blog.csdn.net/sumup/article/details/78942493
今日推荐