C语言 GetIDsOfNames 获取Sheets实例
时间: 2024-01-22 21:21:06 浏览: 104
在 C 语言中,可以使用 COM 技术来操作 Excel 应用程序。使用 COM 技术,需要引用 Excel 的类型库,并使用其中的接口和方法。
要获取 Sheets 实例,可以按照以下步骤进行:
1. 创建 Excel 应用程序对象:
```
CoInitialize(NULL);
IDispatch *pExcelApp;
CLSID clsid;
CLSIDFromProgID(L"Excel.Application", &clsid);
HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&pExcelApp);
```
2. 获取 Workbooks 对象:
```
DISPID dispid;
OLECHAR *member = L"Workbooks";
hr = pExcelApp->GetIDsOfNames(IID_NULL, &member, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
VARIANT vResult;
EXCEPINFO excepInfo;
DISPPARAMS dispParams = {0};
hr = pExcelApp->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispParams, &vResult, &excepInfo, NULL);
IDispatch *pWorkbooks = vResult.pdispVal;
```
3. 获取指定的 Workbook:
```
DISPID dispid;
OLECHAR *member = L"Open";
hr = pWorkbooks->GetIDsOfNames(IID_NULL, &member, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
VARIANTARG args[2];
VariantInit(&args[1]);
args[1].vt = VT_BSTR;
args[1].bstrVal = SysAllocString(L"C:\\test.xlsx");
args[0].vt = VT_BOOL;
args[0].boolVal = VARIANT_TRUE;
DISPID dispID;
hr = pWorkbooks->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dispParams, &vResult, &excepInfo, NULL);
IDispatch *pWorkbook = vResult.pdispVal;
```
4. 获取 Sheets 对象:
```
DISPID dispid;
OLECHAR *member = L"Sheets";
hr = pWorkbook->GetIDsOfNames(IID_NULL, &member, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
DISPPARAMS dispParams = {0};
VARIANT vResult;
EXCEPINFO excepInfo;
hr = pWorkbook->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispParams, &vResult, &excepInfo, NULL);
IDispatch *pSheets = vResult.pdispVal;
```
5. 获取指定的 Sheet:
```
DISPID dispid;
OLECHAR *member = L"Item";
hr = pSheets->GetIDsOfNames(IID_NULL, &member, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
VARIANTARG args[1];
VariantInit(&args[0]);
args[0].vt = VT_I4;
args[0].intVal = 1; // 第一个 Sheet 的索引为 1
DISPPARAMS dispParams = {0};
dispParams.rgvarg = args;
dispParams.cArgs = 1;
VARIANT vResult;
EXCEPINFO excepInfo;
hr = pSheets->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispParams, &vResult, &excepInfo, NULL);
IDispatch *pSheet = vResult.pdispVal;
```
这样,就可以得到 Sheets 实例了。注意,使用完毕后需要释放对象:
```
pExcelApp->Release();
pWorkbooks->Release();
pWorkbook->Release();
pSheets->Release();
pSheet->Release();
CoUninitialize();
```
阅读全文