Search code examples
c++arraysexcelxll

Return two dimensional array to excel from a c++ xll, the come back


First of all I know that the question was already asked here :

return multi dimension array to excel from c++ xll

I have tried to revive the subject, without success. (The OP not being that active lately, never was.) That's why I am asking the question again, sorry in advance.

I coded up a function returning a (row) one dimensional array :

__declspec(dllexport) LPXLOPER12 WINAPI Get1DArray(void)
{
    static XLOPER12 xlArray;
    XLOPER12 xlValues[2];
    xlValues[0].xltype = xltypeNum;
    xlValues[1].xltype = xltypeNum;
    xlValues[0].val.num = 123;
    xlValues[1].val.num = 456;
    xlArray.xltype = xltypeMulti | xlbitDLLFree;
    xlArray.val.array.rows = 1;
    xlArray.val.array.columns = 2;
    xlArray.val.array.lparray = &xlValues[0];
    return static_cast<LPXLOPER12>(&xlArray);
}

that works. I tried the same wrong thing the OP from question I was mentionning above tried (that's how I came across the question of his).

The only doc I have is the msdn for excel sdk, it did not help me. The function I coded, I used an example found on the web. Did not find any for two-dimensional array. I know Steve Dalton's books about xll, did not help.

I suspect multidimensional XLOPER12 arrays stock values in one-dimensional arrays, numbering by rows and columns or columns and rows, but did not succeed in exploiting this intuition...

That's why I am here.


Solution

  • A simple example returning a 5*5 matrix. Don't forget to free the allocated array via the xlAutoFree12 function.

    __declspec(dllexport) LPXLOPER12 WINAPI Get2DArray(void)
    {   
        static XLOPER12 xlArray;
        int rows = 5;
        int cols = 5;
        xlArray.xltype = xltypeMulti | xlbitDLLFree;
        xlArray.val.array.rows = rows;
        xlArray.val.array.columns = cols;
        xlArray.val.array.lparray = reinterpret_cast<LPXLOPER12>(::malloc(rows * cols * sizeof(XLOPER12)));
        for (int r=0;r<rows;r++)
        {
                for (int c=0;c<cols;c++)
                {
                    XLOPER12* var = xlArray.val.array.lparray + ((r* cols) + c);
                    var->xltype = xltypeNum;
                    var->val.num = r*c;
                }
        }
        return &xlArray;
    }