excel导出lua表

来源:互联网 发布:java方法重载的定义 编辑:程序博客网 时间:2024/05/14 16:18
 

phthon导出excel成lua表

分类: lua python excel 1572人阅读 评论(0) 收藏 举报
exceloutputtableexceptionfunctionfloat


1,需安装python 2.7.2

点击下载

 

2,程序用到第三方库xlrd,需要另行安装

点击下载

 

tool\xls2table.py:

[python] view plaincopyprint?
  1. #! /usr/bin/env python  
  2. # -*- coding: cp936 -*-  
  3.   
  4. # convert excel xls file to lua script with table data  
  5. # date/time values formatted as string, int values formatted as int  
  6. # depend on xlrd module  
  7. # fanlix 2008.1.25  
  8. # Modify:  
  9. # 2008.3.18  merged-cell handles: copy data from top-left cell to other cells  
  10.   
  11.   
  12. import xlrd  
  13. import os.path  
  14.   
  15. FLOAT_FORMAT = "%.8f"  
  16.   
  17. SCRIPT_HEAD = '''''-- excel xlstable format (sparse 3d matrix) 
  18. --{ [sheet1] = { [row1] = { [col1] = value, [col2] = value, ...}, 
  19. --                   [row5] = { [col3] = value, }, }, 
  20. --  [sheet2] = { [row9] = { [col9] = value, }}, 
  21. --} 
  22. -- nameindex table 
  23. --{ [sheet,row,col name] = index, .. } 
  24. '''  
  25.   
  26. SCRIPT_END = '''''-- functions for xlstable read 
  27. local __getcell = function (t, a,b,c) return t[a][b][c] end 
  28. function GetCell(sheetx, rowx, colx) 
  29.     rst, v = pcall(__getcell, xlstable, sheetx, rowx, colx) 
  30.     if rst then return v 
  31.     else return nil 
  32.     end 
  33. end 
  34.  
  35. function GetCellBySheetName(sheet, rowx, colx) 
  36.     return GetCell(sheetname[sheet], rowx, colx) 
  37. end 
  38. '''  
  39.   
  40. def gen_table(filename):  
  41.     if not os.path.isfile(filename):  
  42.         raise NameError, "%s is not a valid filename" % filename  
  43.     book = xlrd.open_workbook(filename,formatting_info=True)  
  44.     luaT = {}  
  45.     luaN = {}  
  46.   
  47.     sidx = 0  
  48.     for sheet in book.sheets():  
  49.         sdict = {}  
  50.         ridx = 0  
  51.         for ridx in xrange(sheet.nrows):  
  52.             rdict = {}  
  53.             for cidx in xrange(sheet.ncols):  
  54.                 value = sheet.cell_value(ridx, cidx)  
  55.                 vtype = sheet.cell_type(ridx, cidx)  
  56.                 v = format_value(value, vtype, book)  
  57.                 #print sidx, ridx, cidx, value, vtype, v  
  58.                 if v is not None and value != "":  
  59.                     rdict[cidx] = v  
  60.             if rdict: sdict[ridx] = rdict  
  61.         if sdict: luaT[sidx] = sdict  
  62.   
  63.         # handle merged-cell  
  64.         for crange in sheet.merged_cells:  
  65.             rlo, rhi, clo, chi = crange  
  66.             try:  
  67.                 v = sdict[rlo][clo]  
  68.             except KeyError:  
  69.                 # empty cell  
  70.                 continue  
  71.             if v is None or v == "": continue  
  72.             for ridx in xrange(rlo, rhi):  
  73.                 if ridx not in sdict:  
  74.                     sdict[ridx] = {}  
  75.                 for cidx in xrange(clo, chi):  
  76.                     sdict[ridx][cidx] = v  
  77.         name = sheet.name  
  78.         luaN[name] = sidx  
  79.         luaT[sidx] = sdict  
  80.         sidx += 1  
  81.     #print "--------- luaT:", luaT  
  82.     return luaT, luaN  
  83.   
  84. def format_value(value, vtype, book):  
  85.     ''''' format excel cell value, int?date? 
  86.     '''  
  87.     if vtype == 2:  
  88.         if value == int(value):  
  89.             value = int(value)  
  90.         elif type(value) == float :  
  91.             pass  
  92.     elif vtype == 3:  
  93.         datetuple = xlrd.xldate_as_tuple(value, book.datemode)  
  94.         # time only no date component  
  95.         if datetuple[0] == 0 and datetuple[1] == 0 and datetuple[2] == 0:  
  96.             value = "%02d:%02d:%02d" % datetuple[3:]  
  97.         # date only, no time  
  98.         elif datetuple[3] == 0 and datetuple[4] == 0 and datetuple[5] == 0:  
  99.             value = "%04d/%02d/%02d" % datetuple[:3]  
  100.         else# full date  
  101.             value = "%04d/%02d/%02d %02d:%02d:%02d" % datetuple  
  102.     return value  
  103.   
  104. def format_output(v):  
  105.     s = ("%s"%(v)).encode("gbk")  
  106.     if s[-1] == "]":  
  107.         s = "%s "%(s)  
  108.     return s  
  109.   
  110. def write_table(luaT, luaN, outfile = '-', withfunc = True):  
  111.     ''''' lua table key index starts from 1 
  112.     '''  
  113.     if outfile and outfile != '-':  
  114.         outfp = open(outfile, 'w')  
  115.         outfp.write(SCRIPT_HEAD)  
  116.     else:  
  117.         import StringIO  
  118.         outfp = StringIO.StringIO()  
  119.   
  120.     outfp.write("sheetname = {\n")  
  121.     for k,v in luaN.iteritems():  
  122.         outfp.write("[\"%s\"] = %d,\n"%(format_output(k), v + 1))  
  123.     outfp.write("};\n\n")  
  124.     outfp.write("sheetindex = {\n")  
  125.     for k, v in luaN.iteritems():  
  126.         outfp.write("[%d] = \"%s\",\n" %(v+1, format_output(k)))  
  127.     outfp.write("};\n\n")  
  128.   
  129.     outfp.write("xlstable = {\n")  
  130.     for sidx, sheet in luaT.iteritems():  
  131.         outfp.write("[%d] = {\n"%(sidx + 1))  
  132.         for rowidx, row in sheet.iteritems():  
  133.             outfp.write("\t[%d] = {\n"%(rowidx + 1))  
  134.             for colidx, col in row.iteritems():  
  135.                 try:  
  136.                     if type(col) is int: s = "%d"%(col)  
  137.                     elif type(col) is float: s = FLOAT_FORMAT%(col)  
  138.                     else : s = "[[%s]]"%(format_output(col))  
  139.                     outfp.write("\t\t[%d] = %s,\n"%(colidx + 1, s))  
  140.                 except Exception, e:  
  141.                     raise Exception("Write Table error (%s,%s,%s) : %s"%(sidx+1,rowidx+1,colidx+1,str(e)))  
  142.             outfp.write("\t},\n")  
  143.         outfp.write("},\n")  
  144.     outfp.write("};\n\n")  
  145.   
  146.     if withfunc: outfp.write(SCRIPT_END)  
  147.     outfp.write("\n__XLS_END = true\n")  
  148.     if not outfile or outfile == '-':  
  149.         outfp.seek(0)  
  150.         print outfp.read()  
  151.     outfp.close()  
  152.   
  153. def main():  
  154.     import sys  
  155.     if len(sys.argv) < 2:  
  156.         sys.exit('''''usage: filename outputfile('-' for stdout by default)''')  
  157.     filename = sys.argv[1]  
  158.     try: output = sys.argv[2]  
  159.     except: output = '-'  
  160.     t, n = gen_table(filename)  
  161.     write_table(t, n, output, withfunc = True)  
  162.   
  163. if __name__=="__main__":  
  164.     main()  


 

tool/test.lua:

 

[ruby] view plaincopyprint?
  1. function ParseTable(table)  
  2.     local CodeString = "--玩家道具\n local autoTable = {\n"  
  3.     for line, Data in ipairs(table[1]) do --只读第一页  
  4.         --第一行不读  
  5.         if line > 1 then  
  6.             CodeString = CodeString .. string.format("\t[%d] = {\n", Data[1])  
  7.             CodeString = CodeString .. string.format("\t\ttype = 'voucher',\n")  
  8.             CodeString = CodeString .. string.format("\t\tareaType = 'other',\n")  
  9.             CodeString = CodeString .. string.format("\t\tname = '%s',\n", Data[3])  
  10.             CodeString = CodeString .. string.format("\t\tdescribe = '%s',\n", Data[4])  
  11.             if Data[5] then  
  12.                 CodeString = CodeString .. string.format("\t\teffect = '%s',\n", Data[5])  
  13.             end  
  14.             CodeString = CodeString .. "\t},\n"  
  15.         end  
  16.     end  
  17.     CodeString = CodeString .. "}\n"  
  18.     CodeString = CodeString .. "function GetTable()\n\treturn autoTable\nend\n"  
  19.     return CodeString  
  20. end  
  21. function SaveCode(file, Code)  
  22.     local fd = io.open(file, "w")  
  23.     assert(fd)  
  24.     fd:write(Code)  
  25.     fd:close()  
  26. end  
  27. function gen()  
  28.     local excelfile = "excel/ping-zheng.xls"  
  29.     local outfile = "autocode/voucher.lua"  
  30.     local cmd = string.format([[python 'tool/xls2table.py' '%s']], excelfile)  
  31.     local fd = io.popen(cmd)  
  32.     local loadxls = loadstring(fd:read("*a"))  
  33.     assert(loadxls)  
  34.     loadxls()  
  35.     assert(__XLS_END)  
  36.     fd:close()  
  37.     local Code = ParseTable(xlstable)  
  38.     SaveCode(outfile, Code)  
  39. end  
  40. gen()  
0 0