본문 바로가기

Programming/MFC

[MFC] 엑셀 파일로 저장하기

// this example creates the Excel file C:\DEMO.XLS, puts in a worksheet with two
// columns (one text the other numeric) an appends three no-sense records.  
// 
void MyDemo::Put2Excel()
{
  CDatabase database;
  CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // exactly the same name as in the ODBC-Manager
  CString sExcelFile = "c:\\demo.xls";                // Filename and path for the file to be created
  CString sSql;
   
  TRY
  {
    // Build the creation string for access without DSN
      
    sSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",
                sDriver, sExcelFile, sExcelFile);

    // Create the database (i.e. Excel sheet)
    if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
    {
      // Create table structure
      sSql = "CREATE TABLE demo (Name TEXT,Age NUMBER)";
      database.ExecuteSQL(sSql);

      // Insert data
      sSql = "INSERT INTO demo (Name,Age) VALUES ('Bruno Brutalinsky',45)";
      database.ExecuteSQL(sSql);

      sSql = "INSERT INTO demo (Name,Age) VALUES ('Fritz Pappenheimer',30)";
      database.ExecuteSQL(sSql);

      sSql = "INSERT INTO demo (Name,Age) VALUES ('Hella Wahnsinn',28)";
      database.ExecuteSQL(sSql);
    }     

    // Close database
    database.Close();
  }
  CATCH_ALL(e)
  {
    TRACE1("Driver not installed: %s",sDriver);
  }
  END_CATCH_ALL;
}
</PRE>