C:int到_bstr_t

时间:2012-06-12 00:38:42

标签: c windows excel bstr

我试图用c绘制excel中的一系列情节。问题是当我尝试在循环中制作绘图时,我必须在excel中更改工作表的名称。但这些名称是_bstr_t格式:

    pSheet->Name =name;

我想让名字看起来像(“表号%d”,i),其中我是反击。我尝试使用sprintf,可能还有其他方法,但没有运气。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

首先使用名称创建一个字符数组,然后将其指定给Name。

char arr[25];
sprintf(arr, "Sheet number %d", i);
pSheet->Name = arr;

答案 1 :(得分:0)

类_bstr_t是围绕BSTR数据类型的C ++包装类,它定义为WCHAR *。请参阅示例What's the difference between BSTR and _bstr_t?。如果您正在使用C,那么您对_bstr_t的引用可能不正确,您应该要求转换为BSTR。

以下代码行可以为您做到这一点:

DWORD len;
BSTR  bstrPtr;
char  sheetName[25];

/* Construct the name of your sheet as a regular string */
sprintf(sheetName, "Sheet number %d", i);
/* Count the number of bytes in the WChar version of your name
   by doing a dummy conversion */
len = MultiByteToWideChar(CP_ACP, 0, sheetName, -1, 0, 0);
/* Allocate the BSTR with this size */
bstrPtr = SysAllocStringLen(0, len);
/* Do the actual conversion of the sheetName into BSTR */
MultiByteToWideChar(CP_ACP, 0, sheetName, -1, bstrPtr, len);

/* Do your stuff... */

/* Deallocate the BSTR */
SysFreeString(bstrPtr);

如果您对_bstr_t 的引用正确并且此代码未回答您的问题,请发布您正在使用的头文件的片段,显示name的定义属性。此外,语句pSheet->Name = name不太可能设置Excel工作表的名称,因为这通常涉及调用函数而不是明确设置属性。了解这也需要您提供更多背景信息。