C语言 DISPID_WORKBOOKS_OPEN 打开excel表格封装实例 源码
时间: 2023-07-31 07:05:26 浏览: 107
DialogImage.zip_CDHtmlDialog_CDHtmlDialog 背景
以下是使用 C 语言封装DISPID_WORKBOOKS_OPEN打开Excel表格的示例代码:
```c
#include <windows.h>
#include <ole2.h>
#include <oleauto.h>
#define EXCEL_CLASS_NAME L"EXCEL7"
#define EXCEL_WINDOW_NAME L"Microsoft Excel"
int main()
{
CoInitialize(NULL);
// 获取 Excel 进程 ID
DWORD processId = 0;
HWND excelHwnd = FindWindow(EXCEL_CLASS_NAME, EXCEL_WINDOW_NAME);
if (excelHwnd != NULL)
{
GetWindowThreadProcessId(excelHwnd, &processId);
}
// 获取 Excel 应用程序对象
CLSID clsid = CLSID_NULL;
if (CLSIDFromProgID(L"Excel.Application", &clsid) != S_OK)
{
return -1;
}
IUnknown* pUnk = NULL;
HRESULT hr = GetActiveObject(&clsid, NULL, &pUnk);
if (hr != S_OK)
{
hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**)&pUnk);
if (hr != S_OK)
{
return -1;
}
}
IDispatch* pAppDisp = NULL;
hr = pUnk->QueryInterface(IID_IDispatch, (void**)&pAppDisp);
pUnk->Release();
if (hr != S_OK)
{
return -1;
}
// 获取 Workbooks 对象
DISPID dispid = DISPID_UNKNOWN;
OLECHAR* methodName = L"Workbooks";
hr = pAppDisp->GetIDsOfNames(IID_NULL, &methodName, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
if (hr != S_OK)
{
return -1;
}
VARIANT result;
DISPPARAMS params = { 0 };
hr = pAppDisp->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, ¶ms, &result, NULL, NULL);
if (hr != S_OK)
{
return -1;
}
IDispatch* pBooksDisp = result.pdispVal;
// 打开 Excel 表格
methodName = L"Open";
hr = pBooksDisp->GetIDsOfNames(IID_NULL, &methodName, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
if (hr != S_OK)
{
return -1;
}
params.cArgs = 1;
VARIANTARG vargs[1];
vargs[0].vt = VT_BSTR;
vargs[0].bstrVal = SysAllocString(L"D:\\test.xlsx"); // Excel 表格路径
params.rgvarg = vargs;
hr = pBooksDisp->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL);
if (hr != S_OK)
{
return -1;
}
// 释放资源
pBooksDisp->Release();
pAppDisp->Release();
CoUninitialize();
return 0;
}
```
注意:该代码仅适用于打开已有的 Excel 表格,如果需要创建新的表格并打开,需要使用其他方法。另外,该代码仅在 Windows 平台上测试通过。
阅读全文