我是这样做的:
先将excel中的数据导入到gridview中,再从gridview中读取数据存入数据库。
下面的代码是将excel导入到gridview中,excel版本为97-2003
前台有一个控件fileupload,我把名字改成了file1
另外还要拖一个gridview控件和button控件,在button的单击事件中调用以下函数。
希望对你有帮助。
protected void databind()
{
string strPath = "e:\\yanzheng\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
File1.PostedFile.SaveAs(strPath);
/*string strPath = File1.PostedFile.FileName;*/
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 8.0;IMEX=1'";
OleDbConnection cnnxls = new OleDbConnection(mystring);
cnnxls.Open();
DataTable table = cnnxls.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = table.Rows[0][2].ToString().Trim();
OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [" + tableName + "]", cnnxls);
myDa.Fill(myDs);
GridView1.DataSource = myDs.Tables[0];
GridView1.DataBind();
cnnxls.Close();
}
已发附件,项目要引用那两个DLL,压缩包里的类根据自己的需要修改代码,里面的代码是我之前的项目用的