C语言 GetIDsOfNames 读取 Excel表格顺序使用实例
时间: 2024-01-30 12:04:18 浏览: 85
利用C语言实现顺序表的实例操作
5星 · 资源好评率100%
以下是一个简单的 C 代码示例,演示如何使用 `GetIDsOfNames` 和 `Invoke` 方法来读取 Excel 表格中的数据,并按顺序输出到控制台。
```c
#include <stdio.h>
#include <windows.h>
#include "ole2.h"
#include "oleauto.h"
int main()
{
HRESULT hr;
CLSID clsid;
IDispatch *pExcelApp = NULL, *pWorkbook = NULL, *pWorksheet = NULL, *pRange = NULL;
VARIANT vtWorkbooks, vtWorkbook, vtWorksheets, vtWorksheet, vtRange, vtValue;
int row, col;
// 初始化 COM 库
hr = CoInitialize(NULL);
if (FAILED(hr))
{
printf("CoInitialize failed: %x\n", hr);
return 1;
}
// 获取 Excel 应用程序对象
hr = CLSIDFromProgID(L"Excel.Application", &clsid);
if (FAILED(hr))
{
printf("CLSIDFromProgID failed: %x\n", hr);
CoUninitialize();
return 1;
}
hr = CoCreateInstance(&clsid, NULL, CLSCTX_LOCAL_SERVER, &IID_IDispatch, (void **)&pExcelApp);
if (FAILED(hr))
{
printf("CoCreateInstance failed: %x\n", hr);
CoUninitialize();
return 1;
}
// 打开工作簿
vtWorkbooks.vt = VT_DISPATCH;
vtWorkbooks.pdispVal = pExcelApp;
hr = Invoke(pExcelApp, L"Workbooks", &vtWorkbooks, 1, &vtWorkbook);
if (FAILED(hr))
{
printf("Invoke Workbooks failed: %x\n", hr);
pExcelApp->Release();
CoUninitialize();
return 1;
}
hr = Invoke(pWorkbook, L"Open", L"C:\\test.xlsx", NULL, 0);
if (FAILED(hr))
{
printf("Invoke Open failed: %x\n", hr);
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 获取工作表对象
vtWorksheets.vt = VT_DISPATCH;
vtWorksheets.pdispVal = pWorkbook;
hr = Invoke(pWorkbook, L"Worksheets", &vtWorksheets, 1, &vtWorksheet);
if (FAILED(hr))
{
printf("Invoke Worksheets failed: %x\n", hr);
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 获取 Range 对象
vtRange.vt = VT_BSTR;
vtRange.bstrVal = SysAllocString(L"A1:B2");
hr = Invoke(pWorksheet, L"Range", &vtRange, 1, &vtRange);
if (FAILED(hr))
{
printf("Invoke Range failed: %x\n", hr);
pWorksheet->Release();
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 读取单元格的值并输出到控制台
for (row = 1; row <= 2; row++)
{
for (col = 1; col <= 2; col++)
{
vtValue.vt = VT_I4;
vtValue.lVal = row * 10 + col;
hr = InvokeMethod(pRange, L"Item", &vtValue, 1, &vtValue);
if (FAILED(hr))
{
printf("InvokeMethod Item failed: %x\n", hr);
pRange->Release();
pWorksheet->Release();
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
printf("%d ", vtValue.lVal);
}
printf("\n");
}
// 释放所有对象
VariantClear(&vtValue);
VariantClear(&vtRange);
pRange->Release();
VariantClear(&vtWorksheet);
pWorksheet->Release();
VariantClear(&vtWorksheets);
pWorkbook->Release();
VariantClear(&vtWorkbook);
pExcelApp->Release();
CoUninitialize();
return 0;
}
// Invoke 函数用于调用 COM 对象的方法
HRESULT Invoke(IDispatch *pObj, LPCWSTR szName, VARIANT *pvResult, int cArgs, ...)
{
HRESULT hr;
DISPID dispid;
DISPPARAMS dispparams = {0};
VARIANTARG *pArgs = NULL;
EXCEPINFO excepinfo;
// 获取方法的 DISPID
hr = pObj->GetIDsOfNames(IID_NULL, (LPOLESTR *)&
阅读全文