python合并表

  1 import xlrd, xlwt
  2 
  3 # 读取
  4 rbook = xlrd.open_workbook('提取+病例合并.xlsx')  # 打开文件
  5 print("表1:")
  6 sheet = rbook.sheet_by_index(0)  # 打开对应的表
  7 nrow = sheet.nrows
  8 ncol = sheet.ncols  # 找到行列总数
  9 first_row = sheet.row_values(0)
 10 col_id_list = []
 11 for col in range(ncol):
 12     row_content = first_row[col]
 13     if row_content == "" or row_content == "样例编号" or row_content == "医院编号":
 14         print("" + str(col) + "列:", end="")  # 当前列
 15         col_content = sheet.col_values(col)
 16         print(col_content)  # 列内所有内容
 17         col_id_list.append(col)
 18 print("预处理列:", col_id_list)
 19 # 以下为输出文件内容
 20 wbook = xlwt.Workbook()
 21 wsheet = wbook.add_sheet("new")  # 设置新建表格名字
 22 print()
 23 print("表2:")
 24 sheet2 = rbook.sheet_by_index(1)  # 打开对应的表
 25 nrow2 = sheet2.nrows
 26 ncol2 = sheet2.ncols  # 找到行列总数
 27 first_row2 = sheet2.row_values(0)
 28 col_id_list2 = []
 29 for col in range(ncol2):
 30     row_content = first_row2[col]
 31     if row_content == "" or row_content == "样例编号" or row_content == "医院编号":
 32         print("" + str(col) + "列:", end="")  # 当前列
 33         col_content2 = sheet2.col_values(col)
 34         print(col_content2)  # 列内所有内容
 35         col_id_list2.append(col)
 36 print("预处理列:", col_id_list2)
 37 # 以下为输出文件内容
 38 wbook = xlwt.Workbook()
 39 wsheet = wbook.add_sheet("new")  # 设置新建表格名字
 40 
 41 # 索引合并
 42 new_first_row = first_row + first_row2[2:]
 43 print(first_row)
 44 print(new_first_row)
 45 for col_id, col_content in enumerate(new_first_row):
 46     wsheet.write(0, col_id, col_content)
 47 
 48 for i in range(1, nrow):
 49     for j in range(len(first_row)):
 50         wsheet.write(i, j, sheet.cell_value(i, j))
 51     if sheet.cell_value(i, 1) in sheet2.col_values(1):  # 如果能找到对应样例编号
 52         sheet2_row_id = sheet2.col_values(1).index(sheet.cell_value(i, 1))  # 找到表二的行号
 53         col = len(first_row)
 54         # print("xxxxxxxxxxxxxxxxxx")
 55         for j in range(2, len(first_row2)):
 56             wsheet.write(i, col, sheet2.cell_value(sheet2_row_id, j))
 57             col = col + 1
 58 
 59 wbook.save('output.xls')
 60 
View Code
posted @ 2020-05-19 15:45  淇实是我  阅读(120)  评论(0编辑  收藏  举报