目的:在两个表格中进行筛选,筛选中符合条件的,同时将表格一中有的列添加到符合条件的另一列中。
import xlrd
import xlwt
def read_excel():
#打开文件
# xlrd用来读取xls
matchwork = xlrd.open_workbook('matchfile1.xls')
databaseworkBook = xlrd.open_workbook('database.xls')
# 保存的文件
result_book = xlwt.Workbook(encoding='utf-8', style_compression=0)
result_sheet = result_book.add_sheet('result', cell_overwrite_ok=True)
col = ('名称1', '名称2', '号', '姓名1', '电话1', '姓名2', '电话2', '性别', '类别', '号3', '地址')
for i in range(0, 10):
result_sheet.write(0, i, col[i])
# 取sheet1内容
match_sheet1_content = matchwork.sheet_by_index(0)
database_sheet_content = databaseworkBook.sheet_by_index(0)
# 将需要匹配的多行数据保存到table中
match_table = []
result_table = []
for i in range(match_sheet1_content.nrows):
rows = match_sheet1_content.row_values(i)
match_table.append(rows)
#print(rows[6])
print(len(match_table))
result_row = 1
for i in range(1, len(match_table)):
for j in range(1, database_sheet_content.nrows):
rows = database_sheet_content.row_values(j)
#if match_table[i][3] == rows[0] and (match_table[i][4] == rows[1] or match_table[i][4] == rows[2]):
#if match_table[i][3] == rows[0]:
if (match_table[i][3] == rows[0] and (rows[6].find(match_table[i][0]) != -1 or rows[5].find(match_table[i][0]) != -1)):
# 匹配电话号码
# if(((match_table[i][4] != "" and (match_table[i][4] == rows[1] or match_table[i][4] == rows[2])) or
# (match_table[i][6] != "" and(match_table[i][6] == rows[1] or match_table[i][6] == rows[2])))):
# if (match_table[i][4] == rows[1] or match_table[i][4] == rows[2] or match_table[i][6] == rows[1] or match_table[i][6] == rows[2]) \
# and (match_table[i][4] != "" or match_table[i][6] != ""):
print(i)
print('1' + match_table[i][3] + ' ' + match_table[i][4])
print('2' + rows[0] + ' ' + rows[1] + ' ' + rows[2])
for ii in range(0, 8):
result_sheet.write(result_row, ii, match_table[i][ii])
print('3' + match_table[i][ii])
result_sheet.write(result_row, 9, rows[3])
result_sheet.write(result_row, 10, rows[6])
result_row = result_row + 1
save_path = 'name_address_excel.xls'
result_book.save(save_path)
print('hello')
if __name__ == '__main__':
read_excel()