asp.net中Excel的数据导入
怎样将execl数据导入到数据库Sqlserver里面,我关键是要思路, 代码也可以,请教各位大侠了。小弟先谢谢了!
------解决方案--------------------依次遍历读取excel中的数据,然后依次调用sql,插入到sql server中。
------解决方案--------------------
这是从excel读取数据保存在datatable中
public static DataTable CreateExcelDataSource(string url)
{
DataTable dt = null;
string connetionStr = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + url + ";" + "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";
string strSql = "select * from [excel文件名$]";
OleDbConnection oleConn = new OleDbConnection(connetionStr);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(strSql, connetionStr);
try
{
dt = new DataTable();
oleAdapter.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
oleAdapter.Dispose();
oleConn.Close();
oleConn.Dispose();
}
}
------解决方案--------------------这里是用一个工具栏按钮(打开excel文件)获取要导入的excel文件的路径,用到了openFileDialog控件
private void toolStripButton1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
openFileDialog1.Filter ="excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
url = openFileDialog1.FileName;
//textBox1.Text = url;
}
------解决方案--------------------这里又是一个工具栏按钮(执行导入excel文件),批量导入
private void toolStripButton2_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = CreateExcelDataSource(url);
string conString = "data source=.;initial catalog=数据库名;integrated security=true"; //调用Excel转Sql方法
string sql = "truncate table 数据库表名";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sql, con);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
DataTable dt = CreateExcelDataSource(url); //创建批量DataTable导入Sql
SqlBulkCopy copy = new SqlBulkCopy(conString, SqlBulkCopyOptions.UseInternalTransaction); //指定数据库表名
copy.DestinationTableName = "数据库表名"; //写入Sql
copy.WriteToServer(dt);
}
------解决方案--------------------http://blog.csdn.net/taomanman/article/details/6989076
------解决方案--------------------
http://space.itpub.net/16436858/viewspace-545029
------解决方案-------------------- DataSet _Table = GetTableName(Server.MapPath(@"upload/" + Request.Cookies["sa"].Value + "/" + this.ListBox1.SelectedValue), this.DropDownList1.SelectedValue); //首先获取EXCEL文件路径
string[] list = Request["checkbox"].Split(",".ToCharArray()); 要导入的列,代码不贴了
string CompanyName = string.Empty, Person_in_charge = string.Empty, Mobile = string.Empty, Phone = string.Empty, Fax = string.Empty, E_mail = string.Empty, Address = string.Empty, IMQQ = string.Empty, AliWW = string.Empty, Website = string.Empty;