python读excel示例

来源:互联网 发布:ug数控车编程视频教程 编辑:程序博客网 时间:2024/06/06 02:57

1,read-errno-cfg.py

# -*- coding: utf-8 -*-
'''
Created on 2011-6-25

@author: hgc
'''
from xlrd import open_workbook
from google.protobuf import text_format

# 添加module路径
import sys
sys.path.append("../proto/")

from errno_cfg_pb2 import ErrnoCfgSvrList, ErrnoCfgCliList

strErrnoCfgFile = "../excel/errno.xls"
strCfgCliOB = "../dat/cli/errno-cli.dat" # output binary
strCfgCliOT = "../dat/cli/errno-cli.txt" # output text
strCfgSvrOB = "../dat/svr/errno-svr.dat"
strCfgSvrOT = "../dat/svr/errno-svr.txt"

def CfgCliCmp(objCfg1, objCfg2):
    return objCfg1.u32Val - objCfg2.u32Val

def CfgSvrCmp(objCfg1, objCfg2):
    return objCfg1.u32Val - objCfg2.u32Val

if __name__ == '__main__':
    book = open_workbook(strErrnoCfgFile)
    sheet1 = book.sheet_by_index(1)
   
    objCfgCliList = ErrnoCfgCliList()
    objCfgSvrList = ErrnoCfgSvrList()
   
    for i in range(1, sheet1.nrows):
        if ("" == sheet1.cell_value(i, 0)): # 空行
            break;
       
        # cli
        objCfgCli = objCfgCliList.astErrnoCfg.add()
        objCfgCli.strName = sheet1.cell_value(i, 2)
        objCfgCli.u32Val = int(sheet1.cell_value(i, 3))
        objCfgCli.strDescZH = sheet1.cell_value(i, 4)
        objCfgCli.strDescEN = sheet1.cell_value(i, 5)
       
        # svr
        objCfgSvr = objCfgSvrList.astErrnoCfg.add()
        objCfgSvr.strName = sheet1.cell_value(i, 2)
        objCfgSvr.u32Val = int(sheet1.cell_value(i, 3))
        objCfgSvr.strDescZH = sheet1.cell_value(i, 4)
       
    # 排序
    objCfgCliList.astErrnoCfg.sort(CfgCliCmp)
    objCfgSvrList.astErrnoCfg.sort(CfgSvrCmp)
   
    # cli 输出二进制格式
    fCfgCliOB = open(strCfgCliOB, "wb")
    fCfgCliOB.write(objCfgCliList.SerializeToString())
    fCfgCliOB.close()
   
    # cli 输出可读格式
    fCfgCliOT = open(strCfgCliOT, "w")
    text_format.PrintMessage(objCfgCliList, fCfgCliOT, 0, True, False)
    fCfgCliOT.close()
   
    # svr 输出二进制格式
    fCfgSvrOB = open(strCfgSvrOB, "wb")
    fCfgSvrOB.write(objCfgSvrList.SerializeToString())
    fCfgSvrOB.close()
   
    # svr 输出可读格式
    fCfgSvrOT = open(strCfgSvrOT, "w")
    text_format.PrintMessage(objCfgSvrList, fCfgSvrOT, 0, True, False)
    fCfgSvrOT.close()

    print "done"

2,errno-cfg.proto

enum ErrnoNameBufSZ
{
 ERRNO_NAME_BUF_SZ = 48;
}

enum ErrnoDescBufSZ
{
 ERRNO_DESC_BUF_SZ = 128;
}

message ErrnoCfgSvr
{
 required string strName = 1;
 required uint32 u32Val = 2;
 required string strDescZH = 3;
}

message ErrnoCfgSvrList
{
    repeated ErrnoCfgSvr astErrnoCfg = 1;
}

message ErrnoCfgCli
{
 required string strName = 1;
 required uint32 u32Val = 2;
 required string strDescZH = 3;
 required string strDescEN = 4;
}

message ErrnoCfgCliList
{
    repeated ErrnoCfgCli astErrnoCfg = 1;
}

原创粉丝点击