主题:怎样从Excel中读取数据
zhango
[专家分:0] 发布于 2010-08-22 11:39:00
如何在VC中读取Excel中的某行某列的数据,存到一个变量中,用什么函数,能提供一个小例子更好,谢谢大家!
回复列表 (共2个回复)
沙发
lihun [专家分:190] 发布于 2010-08-25 17:40:00
try
{
_Application app; // app is an _Application object.
_Workbook book; // More object declarations.
_Worksheet sheet;
Workbooks books;
Worksheets sheets;
Range range; // Used for Microsoft Excel 97 components.
LPDISPATCH lpDisp; // Often reused variable.
COleVariant
covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if(!app.CreateDispatch("Excel.Application"))
{
AfxMessageBox("Couldn't CreateDispatch() for Excel");
return;
}
app.SetVisible(TRUE);
lpDisp = app.GetWorkbooks(); // Get an IDispatch pointer.
ASSERT(lpDisp);
books.AttachDispatch(lpDisp); // Attach the IDispatch pointer
// to the books object.
lpDisp = books.Open("C:\\book1.xls", // Test.xls is a workbook.
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional, covOptional,
covOptional, covOptional, covOptional, covOptional ); // Return Workbook's IDispatch
// pointer.
book.AttachDispatch( lpDisp );
lpDisp = book.GetSheets();
sheets.AttachDispatch(lpDisp);
// Get sheet #1 and attach the IDispatch pointer to your sheet
// object.
lpDisp = sheets.GetItem( COleVariant((short)(1)) );
sheet.AttachDispatch(lpDisp);
lpDisp = sheet.GetRange(COleVariant("A1"), COleVariant("A1"));
// sheet
range.AttachDispatch(lpDisp);
// range.SetNumberFormat(COleVariant("@"));
// range.SetItem(COleVariant((long)(1)),COleVariant((long)(1)),COleVariant(LPCTSTR("000666")));
COleVariant varText = range.GetText();
CString csText;
csText.Format("%s",varText.bstrVal);
// Release dispatch pointers.
range.ReleaseDispatch();
sheet.ReleaseDispatch();
// This is not really necessary because
// the default second parameter of AttachDispatch releases
// when the current scope is lost.
} // End of processing.
catch(COleException *e)
{
char buf[1024]; // For the Try...Catch error message.
sprintf(buf, "COleException. SCODE: %08lx.", (long)e->m_sc);
::MessageBox(NULL, buf, "COleException", MB_SETFOREGROUND | MB_OK);
}
catch(COleDispatchException *e)
{
char buf[1024]; // For the Try...Catch error message.
sprintf(buf,
"COleDispatchException. SCODE: %08lx, Description: \"%s\".",
(long)e->m_wCode,(LPSTR)e->m_strDescription.GetBuffer(512));
::MessageBox(NULL, buf, "COleDispatchException",
MB_SETFOREGROUND | MB_OK);
}
catch(...)
{
::MessageBox(NULL, "General Exception caught.", "Catch-All",
MB_SETFOREGROUND | MB_OK);
}
板凳
lihun [专家分:190] 发布于 2010-08-25 17:41:00
通过excel导出的COM接口来操作就行了
我来回复