请参照我写的一个类:
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Excel;
namespace SqlFactory.BI
{
public class CExcel
{
private DateTime beforeTime; //Excel启动之前时间
private DateTime afterTime; //Excel启动之后时间
///
/// 读取Excel数据的代码 add by zfx 2009.4.20
///
///
public System.Data.DataTable CreateExcelDataSource(string excelName)
{
string strCon;
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelName + "; Extended Properties='Excel 8.0;IMEX=1';";
OleDbConnection olecon = new OleDbConnection(strCon);
try
{
OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon);
System.Data.DataTable mydt = new System.Data.DataTable();
myda.Fill(mydt);
return mydt;
}
catch (Exception ex)
{
ex.Message.ToString();
return null;
}
finally
{
olecon.Close();
}
}
//动态读取Excel 根据实际表名读取
public DataSet GetExcelDataSource(string excelName)
{
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelName + "; Extended Properties='Excel 8.0;IMEX=1';";
string sql = "Select * From [{0}]";
OleDbConnection conn = null;
OleDbDataAdapter da = null;
System.Data.DataTable tblSchema = null;
IList
// 初始化连接,并打开
conn = new OleDbConnection(connStr);
conn.Open();
// 获取数据源的表定义元数据
tblSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
tblNames = new List
foreach (DataRow row in tblSchema.Rows)
{
tblNames.Add((string)row["TABLE_NAME"]); // 读取表名
}
// 初始化适配器
da = new OleDbDataAdapter();
// 准备数据,导入DataSet
DataSet ds = new DataSet();
foreach (string tblName in tblNames)
{
da.SelectCommand = new OleDbCommand(String.Format(sql, tblName), conn);
try
{
da.Fill(ds, tblName);
}
catch
{
// 关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return null;
}
}
// 关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return ds;
}
不过对excel文件有要求,excel文件里面智能有一个sheet,且命名为Sheet1;
这样可以把excel文件的内容读入到grid里面去!
希望对您有帮助!
http://support.microsoft.com/kb/321686/zh-cn
给你个参考
用存储过程可以直接访问excel数据的