vs2022 Win32API COM 读取 Excel 表格的工具类
时间: 2023-11-28 19:50:26 浏览: 179
以下是一个基于 Win32API 和 COM 的读取 Excel 表格的工具类示例代码:
```cpp
#include <windows.h>
#include <ole2.h>
#include <oleauto.h>
#include <tchar.h>
class ExcelReader
{
public:
ExcelReader()
{
CoInitialize(NULL);
m_spExcelApp = NULL;
m_spWorkbook = NULL;
m_spWorksheet = NULL;
}
~ExcelReader()
{
if (m_spWorksheet != NULL)
m_spWorksheet->Release();
if (m_spWorkbook != NULL)
m_spWorkbook->Release();
if (m_spExcelApp != NULL)
m_spExcelApp->Release();
CoUninitialize();
}
bool OpenFile(LPCTSTR szFile)
{
HRESULT hr = S_OK;
hr = CoCreateInstance(CLSID_ExcelApplication, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (LPVOID*)&m_spExcelApp);
if (FAILED(hr))
return false;
VARIANT vtFileName;
VariantInit(&vtFileName);
vtFileName.vt = VT_BSTR;
vtFileName.bstrVal = SysAllocString(szFile);
VARIANT vtReadOnly;
VariantInit(&vtReadOnly);
vtReadOnly.vt = VT_BOOL;
vtReadOnly.boolVal = TRUE;
m_spWorkbook = m_spExcelApp->Workbooks->Open(vtFileName, NULL, vtReadOnly, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
if (m_spWorkbook == NULL)
return false;
m_spWorksheet = m_spWorkbook->Worksheets->Item[1];
if (m_spWorksheet == NULL)
return false;
return true;
}
bool ReadData(int nRow, int nCol, CString& str)
{
VARIANT vtRange;
VariantInit(&vtRange);
vtRange.vt = VT_BSTR;
CString strRange;
strRange.Format(_T("%s%d"), ColumnIndexToName(nCol), nRow);
vtRange.bstrVal = SysAllocString(strRange);
IDispatch* pDisp = m_spWorksheet->Cells->Item[vtRange];
if (pDisp == NULL)
return false;
VARIANT vtValue;
VariantInit(&vtValue);
DISPID dispid;
LPTSTR szMember = _T("Value");
hr = pDisp->GetIDsOfNames(IID_NULL, &szMember, 1, LOCALE_USER_DEFAULT, &dispid);
if (FAILED(hr))
return false;
hr = pDisp->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, NULL, &vtValue, NULL, NULL);
if (FAILED(hr))
return false;
str = vtValue.bstrVal;
VariantClear(&vtRange);
VariantClear(&vtValue);
pDisp->Release();
return true;
}
private:
IDispatchPtr m_spExcelApp;
IDispatchPtr m_spWorkbook;
IDispatchPtr m_spWorksheet;
LPCTSTR ColumnIndexToName(int nCol)
{
static TCHAR szName[10];
int nLen = 0;
while (nCol > 0)
{
int nRemainder = (nCol - 1) % 26;
szName[nLen++] = (TCHAR)(_T('A') + nRemainder);
nCol = (nCol - nRemainder) / 26;
}
szName[nLen] = _T('\0');
_tcsrev(szName);
return szName;
}
};
```
使用示例:
```cpp
ExcelReader reader;
if (reader.OpenFile(_T("test.xlsx")))
{
CString str;
reader.ReadData(1, 1, str);
MessageBox(NULL, str, _T("ExcelReader"), MB_OK);
}
```
注意:以上代码仅供参考,具体实现可能需要根据实际情况进行调整。
阅读全文