這個程序就是把Excel當作一個數據庫,使用sql語句進行操作。這個程序通用性不強,不能夠處理任意的Excel文件,大概是因爲把Excel文件當成數據庫,對於文件格式要求的比較嚴格。
程序參考自:http://www.programfan.com/club/showtxt.asp?id=252948
環境是:VC6.0 + Excel2003
過程如下:
用支持MFC的控制檯程序來做個簡單的實驗。
首先,要在stdafx.h頭文件中引入ODBC的頭文件:
#include <afxdb.h>
#include <odbcinst.h>
然後,寫函數。生成一個demo.xls文件,並插入數據,然後從demo.xls中讀取數據,將call price前面幾行求和,結果寫到call price後面單元格內。
void CalculateExcel()
{
CDatabase database;
CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // Excel安裝驅動
CString sExcelFile = "demo.xls";
TRY
{
// 創建進行存取的字符串
CString strSql;
strSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=/"%s/";DBQ=%s",sDriver, sExcelFile, sExcelFile);
// 創建數據庫 (即Excel表格文件)
if(!database.OpenEx(strSql,CDatabase::noOdbcDialog))
{
printf("Excel表格打開失敗/n");
return;
}
// 創建表,並插入值
strSql = "create table demo(A char(20), B double)";
database.ExecuteSQL(strSql);
strSql = "insert into demo(A, B) values('asd', 23)";
database.ExecuteSQL(strSql);
strSql = "insert into demo(A, B) values('sfs', 564.2)";
database.ExecuteSQL(strSql);
strSql = "insert into demo(A, B) values('asfe', 42)";
database.ExecuteSQL(strSql);
strSql = "insert into demo(A) values('call price')"; // call price 計算結果寫到它後面
database.ExecuteSQL(strSql);
// 讀取所有的值,並將前三項數據求和,將結果寫入到call price後面的單元格中
CRecordset rs(&database);
// 設置讀取的查詢語句
strSql = "SELECT * FROM demo";
// 執行查詢語句
rs.Open(CRecordset::forwardOnly, strSql);
printf("begin……/n");
// 獲取查詢結果,並計算
CString strValue1, strValue2;
float sum = 0.0f;
while (!rs.IsEOF())
{
//讀取Excel內部數值
rs.GetFieldValue("A", strValue1);
rs.GetFieldValue("B", strValue2);
if (strValue1 != "call price")
{
sum += atof(strValue2);
printf("%s/t/t%s/n", strValue1, strValue2);
}
// 移到下一行
rs.MoveNext();
}
rs.Close();
// 插入數值
strValue2.Format("%.2f", sum);
strSql = "UPDATE demo SET B='" + strValue2 + "' WHERE A='call price'";
database.ExecuteSQL(strSql);
printf("/nthe result:/n%s/t%s/n", strValue1, strValue2);
printf("/nupdate file end!/n/n");
// 關閉數據庫
database.Close();
}
CATCH_ALL(e)
{
printf("Excel驅動沒有安裝: %s/n", sDriver);
}
END_CATCH_ALL;
}
程序執行結果如下圖:
控制檯上:
創建了Excel表格,並將結果寫入: