用C/C++和Python生成Excel文件
一直都是使用 C/C++ 来编写 CGI ,最近碰到一个需要将数据库记录导出到 excel 文件的需求,在 C/C++ 下基本上没有什么好的解决办法,尤其是在 linux 下,但是时下流行的各种脚本语言却对 excel 文件的操作有不错的支持,比如 perl , python 等( php 下所能找到的组件都会或多或少有些问题,比如单元格内字节 255 限制, excel2003 版本限制等),基于 dui 语言的熟悉程度将 python 嵌入到 C++ 的解决思路也就形成了。
?
Python 下选用的组件是 pyexcelerator ,在 python 的官方网站上就能获得,安装过程这里就掠过了,下面把重要的代码片段贴出来。
excel.py
#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 文件