最近公司给了一批数据,excel格式存储,列头是这样的(字段名简化):
id | c1_2014 | c1_2015 | c1_2016 | c1_2017 | c2_2014 | c2_2015 | c2_2016 | c2_2017 | ...... | c52_2014 | c52_2015 | c52_2016 | c52_2017 |
01 | a11 | a12 | a13 | a14 | b11 | b12 | b13 | b14 | ..... | x11 | x12 | x13 | x14 |
02 | a21 | a22 | a23 | a24 | b21 | b22 | b23 | b24 | ...... | x21 | x22 | x23 | x24 |
通过excel表头可知, 这批数据其实只有25个字段(c1, c2, ....., c52), 只不过是每个字段后面加上了日期(2014, 2015, 2016, 2017)。 因此打算把这批数据导入数据库前先做一下预处理,转换成以下字段格式:
id | year | c1 | c2 | ...... | c52 |
01 | 2014 | a11 | b11 | ...... | x11 |
01 | 2015 | a12 | b12 | ...... | x12 |
01 | 2016 | a13 | b13 | ...... | x13 |
01 | 2017 | a14 | b14 | ...... | x14 |
02 | 2014 | a21 | b21 | ...... | x21 |
02 | 2015 | a22 | b22 | ...... | x22 |
02 | 2016 | a23 | b23 | ...... | x23 |
02 | 2017 | a24 | b24 | ...... | x24 |
想要得到以上结果,具体步骤如下(一些处理的具体细节不赘述)
1)读取列头,获取字段映射表 :原始字段名 --> 新字段名(去掉日期);
2)由步骤1得到新字段名的dict,为每一个新字段名分配一个excel的列标,如A, B, C,......;
3)根据1和2将原始字段名的excel列标映射到新的列标;
4)遍历原始原始数据的每一行,然后根据3将原始值存放到指定excel列位置。
关键是步骤2的实现,即将问题简化为:给定任意自然数得到Excel的列头,以下是我使用python语言实现代码:
alphabet = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
def generate_excel_col_index(num):
if num < 1:
print('输入提示:输入值必须大于1')
return None
else:
dividend = int(num) # 被除数
remainder = 26 if int(dividend % 26) == 0 else int(dividend % 26) # 余数
ls = [remainder]
dividend -= remainder
x = 1
flag = True
while dividend > 0 and flag:
quotient = int(dividend/26**x)
if quotient <= 26:
ls.append(quotient)
flag = False
else:
quotient = 26 if quotient % 26 == 0 else quotient % 26
ls.append(quotient)
dividend -= quotient * (26 ** x)
x += 1
str_ls = [alphabet[y-1] for y in ls]
result = ''.join(str_ls)[::-1]
return result
给定任意一个正整数,得到excel列头的测试结果为:
if __name__ == '__main__':
x = 1352
col = generate_excel_col_index(x)
print("{0} 转换为excel列头为 {1} ".format(x, col))
D:\Programs\Python\Python35\python.exe D:/pyWorkSpace/demo.py
1352 转换为excel列头为 AYZ