C++ excel编程
时间: 2023-07-05 09:31:09 浏览: 191
C++操作Excel
4星 · 用户满意度95%
C++可以使用COM技术来操作Excel,以下是一个简单的示例代码:
```c++
#include <iostream>
#include <windows.h>
#include <ole2.h>
int main() {
// 初始化COM
CoInitialize(NULL);
// 创建Excel对象
IDispatch* pExcelApp = NULL;
CLSID clsid;
CLSIDFromProgID(L"Excel.Application", &clsid);
HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (LPVOID*)&pExcelApp);
if (FAILED(hr)) {
std::cerr << "create Excel object failed" << std::endl;
CoUninitialize();
return 1;
}
// 显示Excel窗口
pExcelApp->PutVisible(VARIANT_TRUE);
// 获取工作簿对象
IDispatch* pWorkbook = NULL;
hr = pExcelApp->GetActiveWorkbook(&pWorkbook);
if (FAILED(hr)) {
std::cerr << "get workbook failed" << std::endl;
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 获取工作表对象
IDispatch* pWorksheet = NULL;
hr = pWorkbook->GetActiveSheet(&pWorksheet);
if (FAILED(hr)) {
std::cerr << "get worksheet failed" << std::endl;
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 写入数据到单元格
VARIANT var;
VariantInit(&var);
var.vt = VT_BSTR;
var.bstrVal = SysAllocString(L"Hello, World!");
hr = pWorksheet->Invoke(dispidSetValue, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL);
if (FAILED(hr)) {
std::cerr << "write data failed" << std::endl;
pWorksheet->Release();
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 保存工作簿
hr = pWorkbook->Invoke(dispidSave, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, ¶ms, NULL, NULL, NULL);
if (FAILED(hr)) {
std::cerr << "save workbook failed" << std::endl;
pWorksheet->Release();
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 1;
}
// 释放资源
VariantClear(&var);
pWorksheet->Release();
pWorkbook->Release();
pExcelApp->Release();
CoUninitialize();
return 0;
}
```
注意:以上代码中的`dispidSetValue`和`dispidSave`需要在调用前获取,以便正确调用Excel对象的方法。
阅读全文