//引入oledb
using System.Data.OleDb;
//读取入口
public static DataTable Query(string excelPath, string sheetName)
{
OleDbConnection conn = CreateConnection(excelPath);
conn.Open();
DataTable dt = new DataTable();
dt = QueryBySheetName(conn, sheetName + "$");
conn.Close();
return dt;
}
//定义连接串
internal static OleDbConnection CreateConnection(string excelPath)
{
return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + excelPath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'");
}
//读取excel指定sheet的数据
private static DataTable QueryBySheetName(OleDbConnection conn, string sheetName)
{
string cmd = "select * from [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
//从datatable插入数据库,具体取值插入代码略
for(int i=0;i
C#操作EXCEL,读取所需数据;再操作数据库,写入数据。