登录
首页精彩阅读使用C#将Excel文件中数据导入SQL Server数据库
使用C#将Excel文件中数据导入SQL Server数据库
2018-01-02
收藏

使用C#将Excel文件中数据导入SQL Server数据库

由于项目中加入了新的功能,可以使管理员向数据库中导入Excel数据。因此,在商品管理这块需要对Excel进行操作,在网上查了些资料,根据项目的实际情况进行了一定的优化,这里简单的介绍下。
C#代码

[csharp] view plain copy

    <span style="font-family:'Microsoft YaHei';font-size:18px;">/// <summary>  
    /// 上传Excel文件,并将数据导入到数据库  
    /// </summary>  
    /// <param name="sender"></param>  
    /// <param name="e"></param>  
    protected void lbtnSure_Click(object sender, EventArgs e)  
    {  
           // 定义变量,并赋初值  
           string url = this.fileUpLoad.PostedFile.FileName;  
           string urlLocation = "";  
      
            // 判断传输地址是否为空  
            if (url == "")  
            {  
                  // 提示“请选择Excel文件”  
                  Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script defer>alert('请选择97~2003版Excel文件!');</script>");  
                  return;  
             }  
      
             // 判断获取的是否为地址,而非文件名  
             if (url.IndexOf("\\") > -1)  
             {  
                 // 获取文件名  
                 urlLocation = url.Substring(url.LastIndexOf("\\") + 1);//获取文件名  
      
             }  
             else  
             {  
                 // url为文件名时,直接获取文件名  
                 urlLocation = url;  
              }  
      
              // 判断指定目录下是否存在文件夹,如果不存在,则创建  
              if (!Directory.Exists(Server.MapPath("~\\up")))  
              {  
                    // 创建up文件夹  
                    Directory.CreateDirectory(Server.MapPath("~\\up"));  
              }  
      
              //在系统中建文件夹up,并将excel文件另存  
              this.fileUpLoad.SaveAs(Server.MapPath("~\\up") + "\\" + urlLocation);//记录文件名到服务器相对应的文件夹中  
      
              // Response.Write(urlLocation);  
      
              // 取得保存到服务器端的文件路径  
              string strpath = Server.MapPath("~\\up") + "\\" + urlLocation;  
      
              // 取得config中的字段  
              string connectionString = ConfigurationManager.AppSettings["Connect"].ToString();  
      
              string strCon = ConfigurationManager.AppSettings["strUpLoad"].ToString();  
      
              // 替换变量  
              strCon = strCon.Replace("$Con$", strpath);  
      
              // 初始化导入Excel对象  
              ImportExcel excel = new ImportExcel();  
                  
              // 调用方法,将Excel文件导入数据库  
              excel.TransferData(strCon, "t_Goods", connectionString);  
      
    }</span>  

TransferData类

[csharp] view plain copy

    <span style="font-family:'Microsoft YaHei';font-size:18px;">public void TransferData(string strCon, string sheetName, string connectionString)         
            {         
                DataSet ds = new DataSet();      
                try        
                {      
                    //获取全部数据              
                    OleDbConnection conn = new OleDbConnection(strCon);      
                    conn.Open();      
                    string strExcel = "";      
                    OleDbDataAdapter myCommand = null;         
                    strExcel = string.Format("select * from [{0}$]", sheetName);      
                    myCommand = new OleDbDataAdapter(strExcel, strConn);      
                    myCommand.Fill(ds, sheetName);      
            
                    //如果目标表不存在则创建,excel文件的第一行为列标题,从第二行开始全部都是数据记录       
                    string strSql = string.Format("if not exists(select * from sysobjects where name = '{0}') create table {0}(", sheetName);   //以sheetName为表名       
          
                    foreach (System.Data.DataColumn c in ds.Tables[0].Columns)      
                    {         
                        strSql += string.Format("[{0}] varchar(255),", c.ColumnName);         
                    }         
                    strSql = strSql.Trim(',') + ")";         
            
                    using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString))         
                    {      
                        sqlconn.Open();         
                        System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand();         
                        command.CommandText = strSql;         
                        command.ExecuteNonQuery();         
                        sqlconn.Close();      
                    }         
                    //用bcp导入数据          
                    //excel文件中列的顺序必须和数据表的列顺序一致,因为数据导入时,是从excel文件的第二行数据开始,不管数据表的结构是什么样的,反正就是第一列的数据会插入到数据表的第一列字段中,第二列的数据插入到数据表的第二列字段中,以此类推,它本身不会去判断要插入的数据是对应数据表中哪一个字段的       
                    using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))         
                    {         
                        bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);         
                        bcp.BatchSize = 100;//每次传输的行数          
                        bcp.NotifyAfter = 100;//进度提示的行数          
                        bcp.DestinationTableName = sheetName;//目标表          
                        bcp.WriteToServer(ds.Tables[0]);      
                    }         
                }         
                catch (Exception ex)         
                {         
                    throw new Exception(ex);         
                }       
            }         
            
            //进度显示          
            void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)         
            {         
                       
            }        
        }       </span> 
Web界面样式


数据分析咨询请扫描二维码

客服在线
立即咨询