execl資料儲存到陣列中

小橋or流水發表於2015-12-30

藉助odbc進行操作execl表格,將execl裡的資料儲存到陣列中,方便接下來的資料處理。

完整工程程式碼,直接可以執行:見連結http://download.csdn.net/detail/u010951938/9384091

#include "stdafx.h"
#include "OdbcExcel.h"
#include "OdbcExcelDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COdbcExcelDlg dialog

COdbcExcelDlg::COdbcExcelDlg(CWnd* pParent /*=NULL*/)
	: CDialog(COdbcExcelDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(COdbcExcelDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void COdbcExcelDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(COdbcExcelDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(COdbcExcelDlg, CDialog)
	//{{AFX_MSG_MAP(COdbcExcelDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_WRITEEXCEL, OnWriteexcel)
	ON_BN_CLICKED(IDC_READEXCEL, OnReadexcel)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COdbcExcelDlg message handlers

BOOL COdbcExcelDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void COdbcExcelDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void COdbcExcelDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR COdbcExcelDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

//建立並寫入Excel檔案
void COdbcExcelDlg::WriteToExcel()
{
	CDatabase database;
	CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // Excel安裝驅動
	CString sExcelFile = "c:\\demo.xls";// 要建立的Excel檔案
	CString sSql;
	
	TRY
	{
		// 建立進行存取的字串
		sSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",
			sDriver,sExcelFile,sExcelFile);
		
		// 建立資料庫 (既Excel表格檔案)
		if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
		{
			// 建立表結構(姓名、飯店、口味評分、環境評分、服務評分)			
			sSql = "CREATE TABLE demo (Name TEXT,Sname TEXT,Taste NUMBER,Environment NUMBER,Service NUMBER)";
			database.ExecuteSQL(sSql);
			
			// 插入數值
			sSql = "INSERT INTO demo (Name,Sname,Taste,Environment,Service) VALUES ('張巨集林','小饞貓',7,8,9)";
			database.ExecuteSQL(sSql);
			sSql = "INSERT INTO demo (Name,Sname,Taste,Environment,Service) VALUES ('肖洪偉','小骨便當'4,5,6)";
			database.ExecuteSQL(sSql);
			sSql = "INSERT INTO demo (Name,Sname,Taste,Environment,Service) VALUES ('蔣渝','天天便當',1,2,3)";
			database.ExecuteSQL(sSql);
		}
		// 關閉資料庫
		database.Close();
	}
	CATCH_ALL(e)
	{
		TRACE1("Excel驅動沒有安裝: %s",sDriver);
	}
	END_CATCH_ALL;
}

// 讀取Excel檔案
void COdbcExcelDlg::ReadFromExcel()
{
	CDatabase database;
	CString sSql;
	CString sItem1, sItem2,sItem3,sItem4,sItem5;
	CString sDriver;
	CString sDsn;
	CString sFile = "C:\\Demo.xls";// 將被讀取的Excel檔名
	
	// 檢索是否安裝有Excel驅動 "Microsoft Excel Driver (*.xls)"
	sDriver = GetExcelDriver();
	if (sDriver.IsEmpty())
	{
		// 沒有發現Excel驅動
		AfxMessageBox("沒有安裝Excel驅動!");
		return;
	}
	// 建立進行存取的字串
	sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",
		sDriver,sFile);
	TRY
	{
		// 開啟資料庫(既Excel檔案)
		database.Open(NULL, false, false, sDsn);
		CRecordset recset(&database);
		// 設定讀取的查詢語句
		sSql = "SELECT Name,Sname,Taste,Environment,Service FROM demo ORDER BY Name";
		
		//執行查詢語句
		recset.Open(CRecordset::forwardOnly, sSql, CRecordset::readOnly);
		
		// 獲取查詢結果
		while (!recset.IsEOF())
		{
			//讀取Excel內部數值
			recset.GetFieldValue("Name", sItem1);
			recset.GetFieldValue("Sname", sItem2);
			recset.GetFieldValue("Taste", sItem3);
			recset.GetFieldValue("Environment", sItem4);
			recset.GetFieldValue("Service", sItem5);
			
			CString strMsg;
			strMsg.Format("Name:%s,Sname:%s,Taste:%s,Environment:%s,Service:%s",sItem1,sItem2,sItem3,sItem4,sItem5);
			AfxMessageBox(strMsg);
			// 移到下一行
			recset.MoveNext();
		}
		// 關閉資料庫
		database.Close();
	}
	CATCH(CDBException, e)
	{
		// 資料庫操作產生異常時...
		AfxMessageBox("資料庫錯誤: " + e->m_strError);
	}
	END_CATCH;
}


// 獲取ODBC中Excel驅動
CString COdbcExcelDlg::GetExcelDriver()
{
	char szBuf[2001];
	WORD cbBufMax = 2000;
	WORD cbBufOut;
	char *pszBuf = szBuf;
	CString sDriver;
	// 獲取已安裝驅動的名稱(涵數在odbcinst.h裡)
	if (!SQLGetInstalledDrivers(szBuf, cbBufMax, &cbBufOut))
		return "";
	// 檢索已安裝的驅動是否有Excel...
	do
	{
		if (strstr(pszBuf, "Excel") != 0)
		{
			//發現 !
			sDriver = CString(pszBuf);
			break;
		}
		pszBuf = strchr(pszBuf, '\0') + 1;
	}
	while (pszBuf[1] != '\0');
	return sDriver;
}

void COdbcExcelDlg::OnWriteexcel() 
{
	WriteToExcel();	
}

void COdbcExcelDlg::OnReadexcel() 
{
	ReadFromExcel();
}

相關文章