File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #导入模块
5
+ import simplejson as json
6
+ import xlwt
7
+
8
+ #从文件(JSON形式)中读取数据返回字典
9
+ def read_file (filename ):
10
+ with open (filename ,'r' ) as fp :
11
+ content = fp .read ()
12
+ #simplejson这个模块还没细看,怎么解码还是需要了解下
13
+ d = json .JSONDecoder ().decode (content )
14
+ return d
15
+
16
+ #生成对应的xls文件
17
+ def gen_xls (d ,filename ):
18
+ fp = xlwt .Workbook ()
19
+ table = fp .add_sheet ('student' ,cell_overwrite_ok = True )
20
+ #试了下,与很多要转utf-8(ASCII码)存文件的情况不同,xls不接受ASCII码形式的存储,直接用字典里面的Unicode就行了,简直好评,不用在特意decode或者encode了
21
+ #想写得更加自动化一些,好复用.本身不太想用两层循环的,不过也不知道有没有更便捷的存储方式(比如整行自动匹配导入,算法是背后优化封装好的,就用了万能的这种方法)
22
+ for n in range (len (d )):
23
+ table .write (n ,0 ,n + 1 )
24
+ m = 0
25
+ for record in d [str (n + 1 )]:
26
+ table .write (n ,m + 1 ,record )
27
+ m += 1
28
+ fp .save ('student.xls' )
29
+ print '写入完毕'
30
+
31
+ #主函数,嘛,最后还是用“丑陋的二重循环”实现了,但是其实也没什么,还是要看场景和优化,毕竟这也不是做查找或者排序,在日常使用中也不用太担心性能问题
32
+ def main ():
33
+ filename = 'student.txt'
34
+ xls_name = 'student.xls'
35
+ d = read_file (filename )
36
+ gen_xls (d ,xls_name )
37
+
38
+ if __name__ == '__main__' :
39
+ main ()
You can’t perform that action at this time.
0 commit comments