版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tsoTeo/article/details/79073830
前台
<div>
<asp:Label ID="lblMessage" runat="server" Text="Label" ForeColor="Red"></asp:Label><br />
<asp:FileUpload ID="inputFile" runat="server" />
<asp:Button ID="btnOk" runat="server" Text="导入SQL Serve数据库" OnClick="btnOk_Click" />
</div>
核心代码
/// <summary>
/// 该方法实现从Excel中导出数据到DataSet中,其中filepath为Excel文件的绝对路径,sheetname为表示那个Excel表,此用Sheet1;
/// </summary>
/// <param name="ds">ds</param>
private void InsertDB(DataSet ds)
{
string CONNECTION_STRING = @"Data Source=192.168.2.5;Initial Catalog=DeputiesPerformingDuty;Integrated Security=false;User ID=sa;Password=1;";
SqlConnection _con = new SqlConnection(CONNECTION_STRING);
SqlCommand cmd = new SqlCommand();
cmd.Connection = _con;
StringBuilder sb = new StringBuilder();
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
sb.Append(" insert into educationinfo(name) values('");
sb.Append(ds.Tables[0].Rows[i].ItemArray[0].ToString() + "' ) ");
cmd.CommandText = sb.ToString();
}
}
_con.Open();
int j = cmd.ExecuteNonQuery();
_con.Close();
if (j > 0)
{
lblMessage.Text = "导入成功";
}
}
/// <summary>
/// get data source from excel file
/// </summary>
/// <returns>dataset ds</returns>
private DataSet GetExcelData()
{
DataSet ds = new DataSet();
inputFile.SaveAs(Server.MapPath("~/" + System.IO.Path.GetFileName(inputFile.PostedFile.FileName)));
string filePath = Server.MapPath("~/" + System.IO.Path.GetFileName(inputFile.PostedFile.FileName));
string connStr03 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;"; ;
string connStr07 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=YES'";
string queryStr = "SELECT * FROM [Sheet1$]";
OleDbConnection conn03 = new OleDbConnection(connStr03);
OleDbConnection conn07 = new OleDbConnection(connStr07);
if (inputFile.HasFile)
{
string fileExt = System.IO.Path.GetExtension(inputFile.FileName);
if (fileExt == ".xls")
{
OleDbDataAdapter myAdapter = new OleDbDataAdapter(queryStr, conn03);
myAdapter.Fill(ds);
}
else if (fileExt == ".xlsx")
{
OleDbDataAdapter myAdapter = new OleDbDataAdapter(queryStr, conn07);
myAdapter.Fill(ds);
}
else
{
lblMessage.Text = "The file is not exist!";
}
}
return ds;
}
后台调用
protected void btnOk_Click(object sender, EventArgs e)
{
DataSet ds = GetExcelData();
InsertDB(ds);
}
如查导入Excel2007时出现
错误信息:未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序。
解决办法:
http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe下载安装就行了。