六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 39|回复: 0

用C/C++和Python生成Excel文件

[复制链接]

升级  25.33%

22

主题

22

主题

22

主题

秀才

Rank: 2

积分
88
 楼主| 发表于 2013-1-26 16:18:18 | 显示全部楼层 |阅读模式
一直都是使用 C/C++ 来编写 CGI ,最近碰到一个需要将数据库记录导出到 excel 文件的需求,在 C/C++ 下基本上没有什么好的解决办法,尤其是在 linux 下,但是时下流行的各种脚本语言却对 excel 文件的操作有不错的支持,比如 perl , python 等( php 下所能找到的组件都会或多或少有些问题,比如单元格内字节 255 限制, excel2003 版本限制等),基于 dui 语言的熟悉程度将 python 嵌入到 C++ 的解决思路也就形成了。
 
Python 下选用的组件是 pyexcelerator ,在 python 的官方网站上就能获得,安装过程这里就掠过了,下面把重要的代码片段贴出来。
excel.py
#-*-coding:gbk-*-from pyExcelerator import * def _toUnicode(s, enc):    return unicode(s, enc) def writeArray(ary, f='array.xls', s='sheet', enc='gbk'):    w = Workbook()    ws = w.add_sheet(_toUnicode(s, enc))    for i in range(len(ary)):       for j in range(len(ary[i])):           style = XFStyle()           fnt = Font()           fnt.height = i * 20           style.font = fnt           ws.write(i, j, _toUnicode(ary[i][j], enc))    w.save(f)    return 0 if __name__ == '__main__':    ary = [['1','2','3'],['4','5','6']]    writeArray(ary, 'excel.xls', '工作簿') 
 
内容很简洁,这里 python 需要做的就是把一个二维数组输出到 excel 文件中, writeArray 函数中 enc 参数表示内容的编码形式
 
下面就到了将 python 嵌入到 CGI 的过程,这里用一个标准可执行程序来代替 CGI 进行演示。
tt.cpp
#include <sstream>#include <fstream>#include <iostream>#include <string>#include <vector>#include <list>#include <algorithm>using namespace std;#include "Python.h"typedef list< list<string> > PyArray;void appendSysPath(const string& path = "."){    PyRun_SimpleString("import sys");    ostringstream oss;    oss<<"if not '"<<path<<"' in sys.path:sys.path.append('"<<path<<"')";    PyRun_SimpleString(oss.str().c_str());}void initPy(){    Py_Initialize();    appendSysPath();}void destroyPy(){    Py_Finalize();}int writeArray(const PyArray& data, const string& fileName, const string& sheetName, const string& encode){    initPy();    try    {        PyObject* mod = PyImport_ImportModule("excel");        if (mod == NULL)        {            throw -1;        }        PyObject* func = PyObject_GetAttrString(mod, "writeArray");        if (func == NULL || !PyCallable_Check(func))        {            throw -2;        }        typedef PyArray::const_iterator pcit;        PyObject* sheet = PyList_New(0);        for (pcit i = data.begin(); i != data.end(); i++)        {            PyObject* row = PyList_New(0);            for (list<string>::const_iterator j = i->begin(); j != i->end(); j++)            {                PyObject* cell = PyString_FromString(j->c_str());                PyList_Append(row, cell);            }            PyList_Append(sheet, row);        }        PyObject* args = PyTuple_New(4);        PyTuple_SetItem(args, 0, sheet);        PyTuple_SetItem(args, 1, PyString_FromString(fileName.c_str()));        PyTuple_SetItem(args, 2, PyString_FromString(sheetName.c_str()));        PyTuple_SetItem(args, 3, PyString_FromString("gbk"));        PyObject* pyRtn = PyEval_CallObject(func, args);        int rtn;        PyArg_Parse(pyRtn, "i", &rtn);        if (rtn != 0)        {            throw -3;        }    }    catch (int e)    {        return e;    }    destroyPy();    return 0;}int main(int argc, char** argv){    PyArray data;    for (int i = 0; i < 10; i++)    {        list<string> tmp;        for (int j = 0; j < 10; j++)        {            tmp.push_back("a");        }        data.push_back(tmp);    }    int ret = writeArray(data, "array.xls", "sheet", "gbk");    cout<<ret<<endl;    return 0;} 
 
这段代码有两个重点。
1.      将当前目录放到 python 的模块搜索路径中。 Python 在嵌入到 C++ 中默认不把当前路径放在模块搜索路径中,这与 python 控制台不同,通过修改 sys.path 属性来配置模块的搜索路径;
2.      将 python 和 C++ 融合在一起。准确的说是在 C++ 和 Python 之间进行数据交换。 PyImport_ImportModule 用来加载 python 模块, PyObject_GetAttrString 用来在模块中找到需要调用的函数地址, PyEval_CallObject 用来执行调用动作, PyArg_Parse 解析返回值, PyTuple_SetItem 则用来构造函数参数。整个过程非常的清晰。
 
Python 程序不需要编译(实际上类似 java , python 执行之前也会将程序代码编译为二进制中间代码),在编译 tt.cpp 文件的时候记得链接 python 库
编译之后执行一下,顺利的话你能在当前目录中看到 array.xls 文件
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表