void CAutoExcelDlg::OnRun()
{
//For optional arguments
COleVariant vOpt(DISP_E_PARAMNOTFOUND, VT_ERROR);
CDaoDatabase db;
CDaoRecordset rs;
CString sConn;
long lNumCols;
//Get a recordset that represents all the records in the Products
//table of the sample Northwind database
sConn =
"C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb";
db.Open(sConn, FALSE, FALSE);
rs.m_pDatabase = &db;
rs.Open(AFX_DAO_USE_DEFAULT_TYPE, "Select * From Products", 0);
lNumCols = rs.GetFieldCount();
//Start a new workbook in Excel
_Application oApp;
oApp.CreateDispatch("Excel.Application");
if (!oApp)
{
AfxMessageBox("Cannot start Excel");
return;
}
Workbooks oBooks = oApp.GetWorkbooks();
_Workbook oBook = oBooks.Add(vOpt);
Worksheets oSheets = oBook.GetWorksheets();
_Worksheet oSheet = oSheets.GetItem(COleVariant((short)1));
Range oRange;
//Transfer the data in the recordset to the worksheet
COleDispatchDriver rs2;
rs2.AttachDispatch((LPDISPATCH) rs.m_pDAORecordset);
oRange = oSheet.GetRange(COleVariant("A2"), vOpt);
oRange.CopyFromRecordset((LPUNKNOWN) rs2.m_lpDispatch, vOpt, vOpt);
rs2.DetachDispatch();
rs2.ReleaseDispatch();
//Add the field names to row 1
CDaoFieldInfo FieldInfo;
for(long i=0; i<=lNumCols-1;i++)
{
oRange = oSheet.GetRange(COleVariant("A1"), vOpt);
oRange = oRange.GetOffset(vOpt, COleVariant(i));
rs.GetFieldInfo(i, FieldInfo, AFX_DAO_PRIMARY_INFO);
oRange.SetValue(COleVariant(FieldInfo.m_strName));
// For Excel 2003, SetValue takes two parameters.
// oRange.SetValue(COleVariant(FieldInfo.m_strName),COleVariant());
}
//Format the worksheet
oRange = oSheet.GetRange(COleVariant("A1"), vOpt);
oRange = oRange.GetResize(COleVariant((short)1),
COleVariant(lNumCols));
Font oFont = oRange.GetFont();
oFont.SetBold(COleVariant((short)TRUE));
oRange = oRange.GetEntireColumn();
oRange.AutoFit();
//Make Excel visible and give the user control
oApp.SetVisible(TRUE);
oApp.SetUserControl(TRUE);
}