python_xlrd模块学习

如果我们要根据一张学校的excel的表,快速的生成一些自动化的c++代码,可以通过id快速的查找学生的姓名,身高等等,并且具有可扩展性,可做如下尝试

1.新建列表

写一个简单的学校的类

#ifndef _SCHOOL_H_
#define _SCHOOL_H_

#include <string>
#include <list>

using namespace std;

 struct student
{
    int id;
    string name;
    int gender;
    int height;
    student(int _id,string _name,int _gender, int _height):id(_id),name(_name),gender(_gender),height(_height){};
};

class school
{
public:
    school();
    ~school();
    int getStudentNum(void);
    string getStudentNamebyId(int id);
private:
    list<student*> mStundentList;
};

#endif

类的实现:

#include "StdAfx.h"
#include "school.h"

#define ADD_STUDENT(id,name,gender,height) mStundentList.push_back(new student(id,name,gender,height))
school::school()
{
/* list start */
/* list end */
}

school::~school()
{
    list<student*>::iterator it = mStundentList.begin();
    
    for(; it!= mStundentList.end();it++)
    {
        delete (*it);
    }
}

int school::getStudentNum(void)
{
    return mStundentList.size();
}

string school::getStudentNamebyId(int id)
{
    list<student*>::iterator it = mStundentList.begin();
    
    for(; it!= mStundentList.end();it++)
    {
        if((*it)->id == id )
        {
            return (*it)->name;
        }
    }
    return "";
}

将school.cpp放在excelTest.py的同目录下的一个Documentation文件夹中,excelTest.py如下:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

'a test module'

_author_ = 'Dani'

import os
import sys
import xlrd

reload(sys)
sys.setdefaultencoding('utf8')     ##just for py2
studentData = []

RESOURCE_LIST_FILE_PATH = './tt.xlsx'
DEFINE_OUT_FILE = './Documentation/school.cpp'

START_PORT = '/* list start */'
END_PORT = '/* list end */'

TAB = '    '

STUDENT_ID_INDEX = 3
STUDENT_NAME_INDEX = 4
STUDENT_GENDER_INDEX = 5
STUDENT_HEIGHT_INDEX = 6

GENDER_MAP = {'m': '0','w':'1'}

class student():
    def __init__(self):
        pass

    def setId(self, _id):
        self.id = _id
    
    def getId(self):
        return self.id

    def setName(self, _name):
        self.name = _name

    def getName(self):
        return self.name
        
    def setGender(self, _gender):
        self.gender = _gender

    def getGender(self):
        return self.gender
        
    def setHeight(self, _height):
        self.height = _height

    def getHeight(self):
        return self.height
        
def LoadStudentListXmlFile():
    global studentData
    
    if (False == os.path.exists(RESOURCE_LIST_FILE_PATH)):
        print(RESOURCE_LIST_FILE_PATH + ' is not exist!')
        return

    xlsData = xlrd.open_workbook(RESOURCE_LIST_FILE_PATH)
    mSheet = xlsData.sheet_by_name('Sheet1')        ##find page

    mRows = mSheet.nrows                            ##行
    mCols = mSheet.ncols                            ##列

    firstRowData = mSheet.row_values(5)

    for i in range(5, mRows):
        rowData = mSheet.row_values(i)

        item = student()
        item.setId(rowData[STUDENT_ID_INDEX])
        item.setName(rowData[STUDENT_NAME_INDEX])
        item.setGender(rowData[STUDENT_GENDER_INDEX])
        item.setHeight(rowData[STUDENT_HEIGHT_INDEX])
        studentData.append(item)                         ##每行的数据可以构造出一个student对象,将所有对象放到一个studentData的list中
        pass
    CreateStudentFiles()
    pass



def get_context_space(lenght, ctx):             ##加空格对齐
    space = ' '
    if (lenght > len(ctx)):
            space = (lenght - len(ctx)) * ' '
    return space

def CreateStudentFiles():
    global studentData
    ctx =''
    # Write TT ini files #
    for j in range(0, len(studentData)):
        tt_ctx = ''
        tt_ctx += TAB + 'ADD_STUDENT('
        tt_ctx += str(studentData[j].getId()).strip()
        tt_ctx += ',' + get_context_space(50, tt_ctx)
        tt_ctx += '"' + str(studentData[j].getName()).strip()+ '"'
        tt_ctx += ',' + get_context_space(50 + 60, tt_ctx)
        tt_ctx += GENDER_MAP[str(studentData[j] .getGender())]
        tt_ctx += ',' + get_context_space(50 + 60 + 50, tt_ctx)
        tt_ctx += str(studentData[j].getHeight()).strip()

        tt_ctx += ');'

        ctx += tt_ctx

        if (j < (len(studentData) - 1)):
            ctx += ' '

        pass

    def_file = open(DEFINE_OUT_FILE, 'r')
    ctx += ' '
    baseCtx     = ''
    replacedCtx = ''

    baseCtx = def_file.readlines();

    def_file.close()
    replaceStart = False

    for line in baseCtx:
        if (line.strip() == START_PORT):               ##起始点开始到结束点为pass,开始时加上ctx,其余读取每行即可
            replaceStart = True
            replacedCtx += line
            replacedCtx += ctx
        else:
            if (replaceStart):
                if (line.strip() == END_PORT):
                    replaceStart = False
                    replacedCtx += line
                else:
                    pass
            else:
                replacedCtx += line

    def_file = open(DEFINE_OUT_FILE, 'w')           ##写入指定cpp文件
    #print (replacedCtx)
    def_file.write(replacedCtx)
    def_file.close()

LoadStudentListXmlFile()

 在大佬的基础上简化和修改,仅学习用

运行后的school.cpp如下:
school::school()
{
/* list start */
    ADD_STUDENT(1,                                 "fsfd",                                                     0,                                                1);
    ADD_STUDENT(2,                                 "dgjdsg",                                                   1,                                                2);
    ADD_STUDENT(3,                                 "1fdfds",                                                   0,                                                3);
    ADD_STUDENT(4,                                 "rgcgdg",                                                   0,                                                4);
    ADD_STUDENT(5,                                 "3regds",                                                   1,                                                23);
    ADD_STUDENT(6,                                 "3red",                                                     1,                                                21);
    ADD_STUDENT(7,                                 "lcl",                                                      1,                                                32);
    ADD_STUDENT(8,                                 "fd",                                                       1,                                                21);
    ADD_STUDENT(9,                                 "fdfdfds",                                                  0,                                                15);
    ADD_STUDENT(10,                                "22df",                                                     0,                                                32);
/* list end */
}

main函数简单调用:

#include"./school.h"
void main()
{
    school msch;
    cout << "has students:"<<msch.getStudentNum()<<endl;
    int id = 7;
    cout<< msch.getStudentNamebyId(id)<<endl;
    cin.get();
}

运行结果:

 在此基础上可以做更复杂的配置,增加更多的选项和对象。

原文地址:https://www.cnblogs.com/doulcl/p/11593784.html