為了將excel數據自動轉換成所需要的erlang數據,聽同事說使用python會很方便簡單,就自學了兩天python,寫了一個比較粗糙的python腳本,不過能用,有什么優化的地方請指教
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys from openpyxl.reader.excel import load_workbook import os import os.path def gen_data(filename): wb = load_workbook( 'dataxlsx/' + filename + '.xlsx' ) # 加載文件所有分頁 sheetnames = wb.get_sheet_names() # 獲取所有分頁的名字列表 ws = wb.get_sheet_by_name(sheetnames[ 0 ]) # 取第一個分頁的數據 # print 'ws:', ws # print "Work Sheet Titile:", ws.title # 分頁名稱 # print "Work Sheet Rows:", ws.max_row # 分頁行數 # print "Work Sheet Cols:", ws.max_column # 分頁列數 content = [] # 數據內容 id_list = [] # ID列表 # ========================start concat need data================= content.append( '%% this file is auto maked!\n' ) content.append( '-module(' + filename + ').\n' ) content.append( '-compile(export_all).\n' ) for i in range ( 4 , ws.max_row + 1 ): # 從表格第三行開始讀取,由于range函數不包含文件尾,所以為了讀到最后一行需+1 for j in range (ws.max_column): if ws[i][j].value = = None : content.append( ' ,""' ) elif j = = 0 : id_list.append( int (ws[i][j].value)) content.append( 'get(' + str (ws[i][j].value).strip() + ') ->\n' ) content.append( ' {r_' + filename + ', ' + str (ws[i][j].value).strip()) else : content.append( ' ,' + str (ws[i][j].value).strip()) content.append( '};\n' ) content.append( 'get(_) ->\n' ) content.append( ' not_match.\n' ) content.append( 'length() ->\n' ) content.append( ' ' + str (ws.max_row - 1 ) + '.\n' ) content.append( 'id_list() ->\n ' + str (id_list) + '.' ) # ==============================end=========================== # 寫入數據 f = file ( './server/' + filename + '.erl' , 'w+' ) f.writelines(content) print 'create new file:' , filename + '.erl' f.close() # 關閉通道 return def start_gen(): # 刪除舊的數據 delnames = os.listdir( './server' ) for delname in delnames: os.remove( './server/' + delname) print 'delete old file:' , delname for _, _, filenames in os.walk( './dataxlsx' ): # 遍歷文件夾 for filename in filenames: # 遍歷文件 find = filename.find( '.xlsx' ) # 返回該文件名稱長度 # print "find is:", find if filename[ 0 ] = = '~' or find = = - 1 : # 文件名以'~'開頭或者找不到文件名, 如以'.'開頭的文件 continue else : split_list = filename.split( '.' ) # 使用'.'分割文件名,獲得[文件名,文件格式] # print split_list gen_data(split_list[ 0 ]) # 用文件名作為參數調用gen_data start_gen() |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/huangxiaoyi/p/7434851.html