Python操作Excel資料並生成新的Excel
阿新 • • 發佈:2022-04-02
根據A列和B列,生成C列
import xlrd from xlutils.copy import copy def main(): rb = xlrd.open_workbook('xxx.xls') rs = rb.sheet_by_index(0) code_dict = {rs.row_values(i)[1]:rs.row_values(i)[0] for i in range(rs.nrows) if i > 0} full_code_dict = {} for key in code_dict.keys(): key_split = key.split('-') if len(key_split) > 1: full_text = "" for i in range(len(key_split)): if full_text != "": full_text += "-" temp_key = "-".join(key_split[0:i+1]) if temp_key in code_dict.keys(): full_text += code_dict[temp_key] full_code_dict[key] = full_text else: full_code_dict[key] = code_dict[key] wb = copy(rb) ws = wb.get_sheet(0) for i in range(rs.nrows): if i > 0: ws.write(i, 2, full_code_dict[rs.row_values(i)[1]]) wb.save('xxx_new.xls') if __name__ == '__main__': main()