专职C++

不能停止的脚步

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  163 Posts :: 7 Stories :: 135 Comments :: 0 Trackbacks

常用链接

留言簿(28)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

由于数值策划给出数值是excel表格,但前台flash程序用的又是json格式。服务器也用了json格式,而json又是utf-8编码的,用C++实现,太痛苦。
鉴于此,尝试用python实现看看。没想到,python实现确实很简单,一个多小时搞定(有搜索事半功倍啊)。
今天我又对它做了一点改进。主要1、是支持float和多表格;2、在excel中用"tablelist"描述要转的表和目标json的文件名称(如图)
修改后的代码:# -*- coding: utf-8 -*-
# 这段代码主要的功能是把excel表格转换成utf-8格式的json文件
#
 lastdate:2011-8-15 14:21 version 1.1 
import os
import sys
import codecs
import xlrd #http://pypi.python.org/pypi/xlrd
if len(sys.argv) != 2 :
    
print "argv count != 2, program exit"
    
print "USAGE: a.py excelfilename"
    exit(0)
print "excel to json"
excelFileName 
= sys.argv[1]
def FloatToString (aFloat):
    
if type(aFloat) != float:
        
return ""
    strTemp 
= str(aFloat)
    strList 
= strTemp.split(".")
    
if len(strList) == 1 :
        
return strTemp
    
else:
        
if strList[1== "0" :
            
return strList[0]
        
else:
            
return strTemp
    
def table2jsn(table, jsonfilename):
    nrows 
= table.nrows
    ncols 
= table.ncols
    f 
= codecs.open(jsonfilename,"w","utf-8")
    f.write(u
"{\n\t\"list\":[\n")
    
for r in range(nrows-1):
        f.write(u
"\t\t{ ")
        
for c in range(ncols):
            strCellValue 
= u""
            CellObj 
= table.cell_value(r+1,c)
            
if type(CellObj) == unicode:
                strCellValue 
= CellObj
            
elif type(CellObj) == float:
                strCellValue 
= FloatToString(CellObj)
            
else:
                strCellValue 
= str(CellObj)
            strTmp 
= u"\""  + table.cell_value(0,c) + u"\":"+ strCellValue
            
if c< ncols-1:
                strTmp 
+= u""
            f.write(strTmp)
        f.write(u
" }")
        
if r < nrows-2:
            f.write(u
",")
        f.write(u
"\n")
    f.write(u
"\t]\n}\n")
    f.close()
    
print "Create ",jsonfilename," OK"
    
return

data 
= xlrd.open_workbook(excelFileName)
table 
= data.sheet_by_name(u"tablelist")
rs 
= table.nrows
for r in range(rs-1):
    
print table.cell_value(r+1,0), "==>", table.cell_value(r+1,2)
    desttable 
= data.sheet_by_name(table.cell_value(r+1,0))
    destfilename 
= table.cell_value(r+1,2)
    table2jsn(desttable,destfilename)

print "All OK"
posted on 2011-08-10 00:07 冬瓜 阅读(7051) 评论(0)  编辑 收藏 引用 所属分类: 原创python

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理