C语言 GetIDsOfNames Range 遍历Excel表格内容实例
时间: 2024-02-06 14:11:34 浏览: 142
读取Excel表数据实例
要遍历 Excel 表格内容,可以使用 Microsoft Office 中提供的 COM 接口。COM 接口提供了一系列的 API 用于操作 Excel 应用程序和工作簿,包括遍历工作表中的单元格内容。
下面是一个简单的示例代码,可以遍历 Excel 工作表中所有单元格的内容:
```c
#include <windows.h>
#include <ole2.h>
#include <oleauto.h>
// 遍历 Excel 工作表中所有单元格的内容
void TraverseExcelRange(LPCTSTR szFileName, LPCTSTR szSheetName)
{
HRESULT hr;
IDispatch* pExcelApp = NULL;
IDispatch* pWorkbooks = NULL;
IDispatch* pWorkbook = NULL;
IDispatch* pWorksheets = NULL;
IDispatch* pWorksheet = NULL;
IDispatch* pRange = NULL;
VARIANT varFileName;
VARIANT varSheetName;
VARIANT varRange;
VARIANT varCellValue;
VARIANT varRowIndex;
VARIANT varColumnIndex;
DISPID dispid;
DISPPARAMS dispparams;
VARIANTARG rgvarg[1];
EXCEPINFO excepinfo;
UINT nArgErr = 0;
// 初始化 COM
hr = CoInitialize(NULL);
if (FAILED(hr)) {
return;
}
// 创建 Excel 应用程序对象
hr = CoCreateInstance(CLSID_Application, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (LPVOID*)&pExcelApp);
if (FAILED(hr)) {
goto CLEANUP;
}
// 设置 Excel 应用程序为不可见状态
VARIANT varVisible;
varVisible.vt = VT_BOOL;
varVisible.boolVal = VARIANT_FALSE;
dispid = 0x1f;
dispparams = { &VARIANT_TRUE, NULL, 1, 1 };
hr = pExcelApp->lpVtbl->Invoke(pExcelApp, dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispparams, NULL, NULL, &nArgErr);
if (FAILED(hr)) {
goto CLEANUP;
}
// 打开 Excel 工作簿
varFileName.vt = VT_BSTR;
varFileName.bstrVal = SysAllocString(szFileName);
dispid = 0x2e;
dispparams = { &varFileName, NULL, 1, 0 };
hr = pExcelApp->lpVtbl->Invoke(pExcelApp, dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, NULL, NULL, &nArgErr);
if (FAILED(hr)) {
goto CLEANUP;
}
pWorkbooks = hr;
// 获取 Excel 工作表
varSheetName.vt = VT_BSTR;
varSheetName.bstrVal = SysAllocString(szSheetName);
dispid = 0x5d;
dispparams = { &varSheetName, NULL, 1, 0 };
hr = pWorkbooks->lpVtbl->Invoke(pWorkbooks, dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &dispparams, NULL, NULL, &nArgErr);
if (FAILED(hr)) {
goto CLEANUP;
}
pWorkbook = hr;
// 获取 Excel 工作表集合
dispid = 0x20;
dispparams = { NULL, NULL, 0, 0 };
hr = pWorkbook->lpVtbl->Invoke(pWorkbook, dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &dispparams, NULL, NULL, &nArgErr);
if (FAILED(hr)) {
goto CLEANUP;
}
pWorksheets = hr;
// 获取 Excel
阅读全文