每天一个小程序—0014题(txt 转 Excel)

每天一个小程序—0014题(txt 转 Excel)

基础知识:
Excel文件的后缀有xls和xlsx,前者是针对2003版本的,2007及其之后的版本是xlsx。

在python中对于这两种不同后缀的文件有不同的库来处理,对于xls用wlrd、xlwt来完成读写,对于xlsx则用openpyxl来处理,并且openpyxl只能处理xlsx文件。

关于openpyxl的用法,这篇博客写得不错:传送门

代码清单:

 1 import openpyxl, re
 2 from openpyxl import Workbook
 3 
 4 def read_to_excel(text):
 5     wb = Workbook()  #创建工作表
 6     ws = wb.create_sheet()  #创建新的sheet页
 7     ws.title = 'student'   #设置sheet页的名字
 8 
 9     row = 1
10     col = 'ABCDE'
11 
12     regex = re.compile(r':[')
13 
14     for line in text:
15         if not line.startswith('{') and not line.startswith('}'):
16             line = line.strip('],
')
17             line = line.strip()
18             line = re.sub(regex, ',', line)
19             data_list = line.split(',')  #逗号分割
20             count = 0
21             for data in data_list:
22                 ws[col[count] + str(row)] = data.strip('"')
23                 count += 1
24             row += 1
25     wb.save('student.xlsx')
26 
27 
28 if __name__ == '__main__':
29     f = open('test.txt')
30     text = f.readlines()
31     read_to_excel(text)

每天一个小程序—0014题(txt 转 Excel)