从页面导入excel数据到sql中 

解决方案 »

  1.   

    使用ASP.NET中的EXCEL驱动程序读取EXCEL中的数据, 再将其写入SQL中即可
      

  2.   

    相关代码如下, 你参考一下, 希望对你有帮助首先这个文件必须上传到服务器,然后读取里面的内容放在ds里面,然后在导入sql 
    具体做法: 
    首先这个文件必须上传到服务器,然后读取里面的内容放在ds里面,然后在导入sql 
    具体做法: 
    using System; 
    using System.Collections; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Web; 
    using System.Web.SessionState; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.UI.HtmlControls; 
    using System.Data.OleDb; 
    using System.Configuration; namespace ETable 

    /// <summary> 
    /// ETable 的摘要说明。 
    /// </summary> 
    public class ETable : System.Web.UI.Page 

    protected System.Web.UI.HtmlControls.HtmlInputFile File1; 
    protected System.Web.UI.WebControls.Label Label1; 
    protected System.Web.UI.WebControls.Button Button1; 
    protected System.Web.UI.WebControls.DataGrid DataGrid1; 
    public Random rd; private void Page_Load(object sender, System.EventArgs e) 

    // 在此处放置用户代码以初始化页面 
    } #region Web 窗体设计器生成的代码 
    override protected void OnInit(EventArgs e) 

    // 
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 
    // 
    InitializeComponent(); 
    base.OnInit(e); 
    } /// <summary> 
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改 
    /// 此方法的内容。 
    /// </summary> 
    private void InitializeComponent() 

    this.Button1.Click += new System.EventHandler(this.Button1_Click); 
    this.Load += new System.EventHandler(this.Page_Load); } 
    #endregion private void Button1_Click(object sender, System.EventArgs e) 

    if (File1.PostedFile!=null) 
    { rd=new Random(1); 
    string filename=DateTime.Now.Date.ToString("yyyymmdd")+DateTime.Now.ToLongTimeString().Replace(":","")+rd.Next(9999).ToString()+".xls"; 
    File1.PostedFile.SaveAs(@Server.MapPath("file/")+filename); 
    //Response.Write(File1.PostedFile.FileName.ToString()); 
    //Response.Write("上传成功"); 
    Label1.Text="文件名为"+filename; 
    string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+Server.MapPath("file")+"/"+filename+";Extended Properties=Excel 8.0" ; 
    OleDbConnection thisconnection=new OleDbConnection(conn); 
    thisconnection.Open(); 
    string Sql="select * from [Sheet1$]"; 
    OleDbDataAdapter mycommand=new OleDbDataAdapter(Sql,thisconnection); 
    DataSet ds=new DataSet(); 
    mycommand.Fill(ds,"[Sheet1$]"); 
    thisconnection.Close(); 
    DataGrid1.DataSource=ds; 
    DataGrid1.DataBind(); 
    string conn1="User ID=sa;Data Source=127.0.0.1;Password=sa;Initial Catalog=index;Provider=SQLOLEDB.1;"; 
    OleDbConnection thisconnection1=new OleDbConnection(conn1); 
    thisconnection1.Open(); 
    int count=ds.Tables["[Sheet1$]"].Rows.Count; for (int i=0;i<count;i++) 

    string id,id_1,id_2,id_3; 
    id=ds.Tables["[Sheet1$]"].Rows[i]["id"].ToString(); 
    id_1=ds.Tables["[Sheet1$]"].Rows[i]["id_1"].ToString(); 
    id_2=ds.Tables["[Sheet1$]"].Rows[i]["id_2"].ToString(); 
    id_3=ds.Tables["[Sheet1$]"].Rows[i]["id_3"].ToString(); 
    string excelsql="insert into excel(id,id_1,id_2,id_3) values ('"+id+"','"+id_1+"','"+id_2+"','"+id_3+"') "; 
    OleDbCommand mycommand1=new OleDbCommand(excelsql,thisconnection1); 
    mycommand1.ExecuteNonQuery(); 

    Response.Write("更新成功"); 
    thisconnection1.Close(); 
    //FileStream fileStream = new FileStream(@Server.MapPath("file/")+filename); 
    System.IO.File.Delete(@Server.MapPath("file/")+filename); } 



    C# using System; 
    using System.Collections; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Web; 
    using System.Web.SessionState; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.UI.HtmlControls; 
    using System.Data.OleDb; 
    using System.Configuration; namespace ETable 

    /// <summary> 
    /// ETable 的摘要说明。 
    /// </summary> 
    public class ETable : System.Web.UI.Page 

    protected System.Web.UI.HtmlControls.HtmlInputFile File1; 
    protected System.Web.UI.WebControls.Label Label1; 
    protected System.Web.UI.WebControls.Button Button1; 
    protected System.Web.UI.WebControls.DataGrid DataGrid1; 
    public Random rd; private void Page_Load(object sender, System.EventArgs e) 

    // 在此处放置用户代码以初始化页面 
    } #region Web 窗体设计器生成的代码 
    override protected void OnInit(EventArgs e) 

    // 
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 
    // 
    InitializeComponent(); 
    base.OnInit(e); 
    } /// <summary> 
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改 
    /// 此方法的内容。 
    /// </summary> 
    private void InitializeComponent() 

    this.Button1.Click += new System.EventHandler(this.Button1_Click); 
    this.Load += new System.EventHandler(this.Page_Load); } 
    #endregion private void Button1_Click(object sender, System.EventArgs e) 

    if (File1.PostedFile!=null) 
    { rd=new Random(1); 
    string filename=DateTime.Now.Date.ToString("yyyymmdd")+DateTime.Now.ToLongTimeString().Replace(":","")+rd.Next(9999).ToString()+".xls"; 
    File1.PostedFile.SaveAs(@Server.MapPath("file/")+filename); 
    //Response.Write(File1.PostedFile.FileName.ToString()); 
    //Response.Write("上传成功"); 
    Label1.Text="文件名为"+filename; 
    string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+Server.MapPath("file")+"/"+filename+";Extended Properties=Excel 8.0" ; 
    OleDbConnection thisconnection=new OleDbConnection(conn); 
    thisconnection.Open(); 
    string Sql="select * from [Sheet1$]"; 
    OleDbDataAdapter mycommand=new OleDbDataAdapter(Sql,thisconnection); 
    DataSet ds=new DataSet(); 
    mycommand.Fill(ds,"[Sheet1$]"); 
    thisconnection.Close(); 
    DataGrid1.DataSource=ds; 
    DataGrid1.DataBind(); 
    string conn1="User ID=sa;Data Source=127.0.0.1;Password=sa;Initial Catalog=index;Provider=SQLOLEDB.1;"; 
    OleDbConnection thisconnection1=new OleDbConnection(conn1); 
    thisconnection1.Open(); 
    int count=ds.Tables["[Sheet1$]"].Rows.Count; for (int i=0;i<count;i++) 

    string id,id_1,id_2,id_3; 
    id=ds.Tables["[Sheet1$]"].Rows[i]["id"].ToString(); 
    id_1=ds.Tables["[Sheet1$]"].Rows[i]["id_1"].ToString(); 
    id_2=ds.Tables["[Sheet1$]"].Rows[i]["id_2"].ToString(); 
    id_3=ds.Tables["[Sheet1$]"].Rows[i]["id_3"].ToString(); 
    string excelsql="insert into excel(id,id_1,id_2,id_3) values ('"+id+"','"+id_1+"','"+id_2+"','"+id_3+"') "; 
    OleDbCommand mycommand1=new OleDbCommand(excelsql,thisconnection1); 
    mycommand1.ExecuteNonQuery(); 

    Response.Write("更新成功"); 
    thisconnection1.Close(); } 


    }
      

  3.   

    用动态路径如何实现?是什么意思? 
    以下是我的一个真实的例子,供参考! 
    <tr> 
    <td align="right"> 选择附件: </td> 
    <td> 
    <INPUT id="File1" type="file" size="15" name="File1" runat="server"> <FONT face="宋体"> &nbsp; </FONT> 
    <asp:button id="btnReadData" runat="server" Width="55px" Text="读取"> </asp:button> <FONT face="宋体"> &nbsp; </FONT> <asp:button id="btnSave" runat="server" Width="59px" Text="导入"> </asp:button> </td> 
    </tr> 
    <tr> 
    <td align="center" valign="top"> <asp:datagrid id="dgExportProject" runat="server" Width="95%" BorderWidth="1px" BackColor="White" 
    BorderColor="#CC9966" BorderStyle="None" CellPadding="4"> 
    <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"> </FooterStyle> 
    <SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"> </SelectedItemStyle> 
    <ItemStyle ForeColor="#330099" BackColor="White"> </ItemStyle> 
    <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"> </HeaderStyle> 
    <PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"> </PagerStyle> 
    </asp:datagrid> </td> 
    </tr> private void btnReadData_Click(object sender, System.EventArgs e) 

    // 获取Excep文件的完整路径 
    string fileName = System.IO.Path.GetFileName(File1.PostedFile.FileName);  
    string filePath = ""; 
    if(this.File1.Value == "") 

    Comm.Jscript.Alert("请先选择您要导入的文件!"); 

    else 

    int index = fileName.LastIndexOf("."); 
    if(index >  0) 

    if(fileName.Substring(index) == ".xls") 

    DateTime now = DateTime.Now;  
    fileName = now.ToShortDateString() + now.ToLongTimeString();  
    fileName = fileName.Replace("-","").Replace(":","").Replace(" ",""); 
    filePath = @"../uploads/" + fileName + ".xls"; 
    this.File1.PostedFile.SaveAs(Server.MapPath(filePath)); } 
    else 

    Comm.Jscript.Alert("读入的文件不是XLS"); 



    if(filePath != "") 

    fileName = Request.MapPath(filePath); string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0"; 
    string query = "SELECT * FROM [Sheet1$]"; 
    OleDbCommand oleCommand = new OleDbCommand(query, new OleDbConnection(strConn)); 
    OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand); 
    DataSet myDataSet = new DataSet(); // 将 Excel 的[Sheet1]表内容填充到 DataSet 对象 
    try 

    oleAdapter.Fill(myDataSet,"[Sheet1$]"); 
    // 数据绑定 
    this.dgExportProject.DataSource = myDataSet; 
    this.dgExportProject.DataMember = "[Sheet1$]"; 
    this.dgExportProject.DataBind(); this.dgExportProject.Visible = true; 
    this.btnSave.Visible = true; 

    catch(Exception exx) 

    Response.Write(exx.Message); 
    Comm.Jscript.Alert("注意:请用默认的Sheet1$页名称!"); 

    finally 

    if(File.Exists(filePath)) 

    File.Delete(filePath); 



    } private void btnSave_Click(object sender, System.EventArgs e) 

    //dgExportProject取出所有数据,保存到项目/客户数据库中 
    if(this.ddlProjectType.SelectedIndex  < 1) 

    Comm.Jscript.Alert("请选择项目类型!"); 
    return; 

    else 

    string projectId = String.Empty; 
    string projectName = String.Empty; 
    string toucher = String.Empty; 
    string tel = String.Empty; 
    string email = String.Empty; 
    string manager = String.Empty; 
    string area = String.Empty; 
    int projectTypeId = int.Parse(this.ddlProjectType.SelectedItem.Value); 
    dccsData.ProjectInfo project = new dccsData.ProjectInfo(); 
    using(SqlConnection sqlConn = new SqlConnection(dccsData.Config.StrConn)) 

    try 

    if(sqlConn.State == ConnectionState.Closed) 

    sqlConn.Open(); 
    } foreach(DataGridItem item in this.dgExportProject.Items) 

    if(item.Cells.Count == 7) 

    projectId = item.Cells[0].Text.Trim().Replace("&nbsp;"," "); 
    projectName = item.Cells[1].Text.Trim().Replace("&nbsp;"," "); 
    toucher = item.Cells[2].Text.Trim().Replace("&nbsp;"," "); 
    tel = item.Cells[3].Text.Trim().Replace("&nbsp;"," "); 
    email = item.Cells[4].Text.Trim().Replace("&nbsp;"," "); 
    manager = item.Cells[5].Text.Trim().Replace("&nbsp;"," "); 
    area = item.Cells[6].Text.Trim().Replace("&nbsp;"," "); 
    //将上述值写入到数据库 
    if(projectId != "&nbsp;" && projectId != String.Empty) 

    project.Insert(projectId,projectName,toucher,tel,email,projectTypeId,manager,area,sqlConn); 


    else 

    Comm.Jscript.Alert("注意:请按照模板格式导入项目信息!"); 
    return; 

    } } 
    catch(Exception exx) 

    Response.Write(exx.Message); 

    finally  

    if(sqlConn.State == ConnectionState.Open) 

    sqlConn.Close(); 


    } this.dgExportProject.Visible = false; 
    this.btnSave.Visible = false; 


     
     
    思路是先把 excel文件传到服务器再读,读完删除
    见http://topic.csdn.net/u/20071224/09/0527e1b5-7c2c-4ee0-97d1-961f8c8c2cf4.html