|

楼主 |
发表于 2012-10-25 12:52
|
显示全部楼层
//创建excel连接对象
//使用后,需要调用者free
wkCom CreateSqlConnection(string strExcelPath, array flds)
{
//使用Scripting.FileSystemObject判断文件是否存在
wkCom fs;
fs.create("Scripting.FileSystemObject");
bool bExist = fs.FileExists(strExcelPath);
fs.free();
//不存在,则创建
if (!bExist)
{
wkCom excel;
//创建Excel组件对象
excel.create("Excel.Application");
excel.putProperty("visible", false); //设为不可见
//新建Excel表
wkCom workBook1 = excel.Workbooks().Add(true);
//把字段填到表格的第一行中
wkCom sheets = workBook1.WorkSheets();
wkCom sheet1 = sheets.Item(1);
int i = 0;
for (i = 0; i < flds.getSize(); ++i)
{
sheet1.Cells().Item(1, i+1).putProperty("Value", flds[ i ]); //excel表格下标从1开始,所以i+1
}
//保存并关闭
workBook1.Close(true, strExcelPath, 0);
//退出
excel.Quit();
//别忘记释放新建的Excel对象
excel.free();
}
//通过adodb连接
wkCom conn;
conn.create("Adodb.Connection");
conn.putProperty("ConnectionString", "Provider=Microsoft.Ace.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" + strExcelPath);
return conn;
}
string GetFlds(array& flds)
{
string sr;
for (int ic = 0; ic < flds.getSize(); ++ic)
{
if (ic) sr += ",";
sr += flds[ ic ];
}
return sr;
}
void main()
{
string path = "F:\\atest.xls";
array flds = {"layerID", "layerName"};
wkCom conn = CreateSqlConnection(path, flds);
conn.Open();//打开数据库连接
string sql1 = "insert into [Sheet1$](" + GetFlds(flds) + ")";
string sql;
//插入10条记录
int i = 0;
for (i = 0; i < 10; ++i)
{
string sql2;
sql2.format("'%d', 'test%d'", i+1, i+1);
sql = sql1 + " values (" + sql2 + ")";
//trace("\n" + sql);
conn.execute(sql);
}
wkCom rs;
rs.create("ADODB.RecordSet");
sql = "select * from [Sheet1$]";
rs.Open(sql,conn,3,3);
//遍历
while(!rs.Eof())
{
string sId = rs.Collect(0);
string sName = rs.Collect(1);
trace("LayerId: %s, LayerName: %s\n", sId, sName);
rs.MoveNext();
}
rs.close();
conn.close();//关闭数据库连接
rs.free();
conn.free();
}
|
|