正如 AnotherParker 所暗示的那样,xlfGetWorkbook 将工作表名称作为长度前缀字符串返回,因此要在函数中使用它,您需要将其转换为空分隔字符串。
此外,xlfGetWorkbook 在工作表名称前加上 [] 括号中的工作簿名称,因此您需要将其剥离以获取实际的工作表名称。
这是一个完整的 C 语言示例,没有使用任何风格的框架,它在 Activesheet 的第一列中输出工作表名称。
int __stdcall ListSheetsD (void)
{
static XLOPER12 xWorkbook;
XLOPER12 xRef, xNumParm, xAutoFit, xFalse, xlCell[10], xlArray;
int rc, i, iSheets;
size_t fullnamelen, sheetnamelen;
wchar_t *fullname, *sheetname;
XCHAR *ptr;
OLECHAR buffer[100];
OLECHAR *function = L"ListSheetsD";
xNumParm.xltype = xltypeNum;
xNumParm.val.num = 1;
rc = Excel12 ( xlfGetWorkbook, (LPXLOPER12)&xWorkbook, 1, (LPXLOPER12)&xNumParm);
if ( rc != xlretSuccess )
{
swprintf ( buffer, 100, L"xlfGetWorkbook. rc=%d", rc );
MessageBox (NULL, buffer, function, MB_OK | MB_SETFOREGROUND );
}
//Get Number of Sheets
iSheets = xWorkbook.val.array.columns;
for ( i = 0; i < iSheets; i++ )
{
if ( i < 10 )
{
//Pickup Sheet Name (format: [Book.xls]Sheet1) & set it up as a Null Delimited String
fullnamelen = xWorkbook.val.array.lparray[i].val.str[0];
fullname = (wchar_t *) malloc ( (fullnamelen + 2) * sizeof (wchar_t) );
memcpy (fullname, (xWorkbook.val.array.lparray[i].val.str + 1),
(fullnamelen) * sizeof(wchar_t));
fullname[fullnamelen] = L'\0';
//Extract Sheet Name (format: Sheet1) & set it up as a Length Prefixed String
sheetname = (wchar_t *) malloc ( (fullnamelen + 2) * sizeof (wchar_t) );
ptr = wcschr (fullname, L']');
sheetnamelen = wcslen (ptr);
wcscpy ( sheetname, ptr );
sheetname[0] = sheetnamelen;
//Setup Output Row
xlCell[i].xltype = xltypeStr;
xlCell[i].val.str = sheetname;
free (fullname);
}
}
if ( i > 10 ) i = 10;
xlArray.xltype = xltypeMulti;
xlArray.val.array.rows = i;
xlArray.val.array.columns = 1;
xlArray.val.array.lparray = &xlCell[0];
xRef.xltype = xltypeSRef;
xRef.val.sref.count = 1;
xRef.val.sref.ref.rwFirst = 0;
xRef.val.sref.ref.rwLast = i - 1;
xRef.val.sref.ref.colFirst = 0;
xRef.val.sref.ref.colLast = 0;
rc = Excel12 ( xlSet, 0, 2, (LPXLOPER12)&xRef, (LPXLOPER12)&xlArray );
if ( rc != xlretSuccess )
{
swprintf ( buffer, 100, L"xlSet. Error=%d", rc );
MessageBox (NULL, buffer, function, MB_OK | MB_SETFOREGROUND );
}
rc = Excel12 (xlFree, NULL, 2, &xWorkbook, &xlArray );
if ( rc != xlretSuccess )
{
swprintf ( buffer, 100, L"xlFree. rc=%d", rc );
MessageBox (NULL, buffer, function, MB_OK | MB_SETFOREGROUND );
}
rc = Excel12 ( xlcSelect, 0, 1, (LPXLOPER12)&xRef );
if ( rc != xlretSuccess )
{
swprintf ( buffer, 100, L"xlcSelect. rc=%d", rc );
MessageBox (NULL, buffer, function, MB_OK | MB_SETFOREGROUND );
}
xAutoFit.xltype = xltypeNum;
xAutoFit.val.num = 3;
xFalse.xltype = xltypeBool;
xFalse.val.xbool = 0;
rc = Excel12 ( xlcColumnWidth, 0, 4, &xNumParm, (LPXLOPER12)&xRef, &xFalse, &xAutoFit );
if ( rc != xlretSuccess )
{
swprintf ( buffer, 100, L"xlcColumnWidth. rc=%d", rc );
MessageBox (NULL, buffer, function, MB_OK | MB_SETFOREGROUND );
}
return 1;
}