1.在页面上添加一个FileUpload控件和一个Button按钮,分别命名为:FileUpload1、btnUpload。
2.双击Button在btnUpload_Click事件中添加一下代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile.FileName.ToString() != "" && FileUpload1.PostedFile.FileName.ToString().Substring((FileUpload1.PostedFile.FileName.ToString().Length - 3), 3) == "xls")
{
string strFileName;
DateTime mydatetime = new DateTime();
mydatetime = DateTime.Now;
strFileName = mydatetime.Year.ToString() + mydatetime.Month.ToString() + mydatetime.Day.ToString() +
mydatetime.Hour.ToString() + mydatetime.Minute.ToString() + mydatetime.Second.ToString() + ".xls";
string path = HttpContext.Current.Server.MapPath("temp\\");
FileUpload1.SaveAs(path + strFileName);
//写一个UpData方法,用来在数据库中添加数据
UpData(path + strFileName);
Response.Write("<script>alert('导入成功!');</script>");
}
else
{
Label1.Text = "请选择一个Excel文件!";
}
}
3.写一个UpData方法,用来在数据库中添加数据
private void UpData(string UploadFileName)
{
string OleDbstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + UploadFileName + "';Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
OleDbConnection OleDbcon = new OleDbConnection();
OleDbcon.ConnectionString = OleDbstr;
OleDbcon.Open();
OleDbCommand OleDbcmd = new OleDbCommand("select * from [sheet1$]", OleDbcon);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = OleDbcmd;
DataSet ds = new DataSet();
DataTable MyTable = ds.Tables.Add("sheet1$");
da.Fill(ds, "sheet1$");
OleDbcon.Close();
for (int i = 0; i < MyTable.Rows.Count; i++)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sqlstr = "INSERT INTO Table (XXX) values ('"+MyTable.Rows[i][0].ToString()+"')";
SqlCommand cmd = new SqlCommand(sqlstr,conn);
conn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
throw new ApplicationException(e.ToString());
}
finally
{
conn.Close();
}
}
}
![](http://www.nextsoft.cn/images/nextsoft-ligth.png)