【问题标题】:C: int to _bstr_tC: int 到 _bstr_t
【发布时间】:2012-06-12 00:38:41
【问题描述】:

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

    pSheet->Name =name;

我想让 name 看起来像 ("Sheet number %d",i),其中 i 是计数器。我尝试使用 sprintf 和其他方法,但没有运气。

任何帮助将不胜感激!

【问题讨论】:

标签: c windows excel bstr


【解决方案1】:

先用名字创建一个字符数组,然后把它赋值给Name。

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

【讨论】:

    【解决方案2】:

    _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 的引用是正确的,并且此代码没有回答您的问题,那么请发布您正在使用的头文件的 sn-p,显示 name 的定义属性。此外,pSheet->Name = name 语句不太可能设置 Excel 工作表的名称,因为这通常涉及调用函数而不是简单地设置属性。理解这一点也需要您提供更多背景信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多