描述:
为了在程序中实现导入EXCEL数据的功能,我写了下面一段代码,但是在导入完成后EXCEL虽然成功退出了(在任务管理器中可以看到对应的进程的确是被结束了),但其所占内存并没有被释放,非要把整个程序关了才能释放。调试了很久实在不知道问题出在哪里,不知道有哪位大虾可以指教一下?因为EXCEL数据非常多,所占的内存至少有100MB左右。谢谢!
_Application ExcelApp;
Workbooks wbsMyBooks;
_Workbook wbMyBook;
Worksheets wssMysheets;
// create excel 2000 server(to start up excel)
if (!ExcelApp.CreateDispatch("Excel.Application", NULL))
{
::AfxMessageBox(_T("创建Excel服务失败!"), MB_ICONERROR, -1);
exit(1);
}
// use the template file to create a new document
wbsMyBooks.AttachDispatch(ExcelApp.GetWorkbooks(), true);
CString strXLTFilename = oFileDialog.GetPathName();
wbMyBook.AttachDispatch(wbsMyBooks.Add(_variant_t((LPCTSTR)strXLTFilename)));
// get worksheets
wssMysheets.AttachDispatch(wbMyBook.GetWorksheets(), true);
_Worksheet wsMysheet;
Range rgMyRge;
for(INT nIndex = 1; nBureauSerialNumber != 0 && nIndex <= wssMysheets.GetCount(); nIndex++)
{
wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t((LONG)nIndex)));
rgMyRge.AttachDispatch(wsMysheet.GetCells(), true);
...
//释放对象
rgMyRge.ReleaseDispatch();
wsMysheet.ReleaseDispatch();
}
...
COleVariant covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
wbMyBook.SetSaved(TRUE);
wbMyBook.Close(covFalse, covOptional, covOptional);
wbsMyBooks.Close();
ExcelApp.Quit();
wssMysheets.ReleaseDispatch();
wbMyBook.ReleaseDispatch();
wbsMyBooks.ReleaseDispatch();
ExcelApp.ReleaseDispatch();
HWND hwndExcel;
hwndExcel = ::FindWindow("XLMain", NULL);
if(hwndExcel == NULL)
{
long lError = GetLastError();
CString strMessage;
strMessage.Format("FindWindow error code = %d", lError);
AfxMessageBox(strMessage);
}
else
{
DWORD pid;
DWORD dThread = GetWindowThreadProcessId(hwndExcel, &pid);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
TerminateProcess(hProcess, 0);
}