【问题标题】:how to import multiple excel sheets into 2 sql server tables?如何将多个excel表导入2个sql server表?
【发布时间】:2014-06-27 18:14:46
【问题描述】:

我有一个 excel 文件,其中包含 2 个不同的工作表作为fundmodelrate 和 project。现在我想将这 2 个不同的工作表值导入 2 个不同的 sql 表(k2_fundmodelrate,k2_project)。我只能在使用 1 时进行导入表和 1 个表,但我希望在按钮单击事件时同时在两个表上导入两个表值。 我的代码如下:

private String strConnection = "Data Source=kuws4;Initial Catalog=jes;User ID=sa;Password=******";               
        protected void btnSend_Click(object sender, EventArgs e)
        {

            string path = fileuploadExcel.PostedFile.FileName;

            string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\fmr.xls;Extended Properties=Excel 12.0;Persist Security Info=False";

            OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

            OleDbCommand cmd = new OleDbCommand("Select * from [FundModelRate$]", excelConnection);
            //OleDbCommand cmd1 = new OleDbCommand("Select * from [FundModelRate$],  [Project$]", excelConnection);
            excelConnection.Open();
            OleDbDataReader dReader;
            dReader = cmd.ExecuteReader();
            SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);

            sqlBulk.DestinationTableName = "K2_FundModelRate";
           // sqlBulk.DestinationTableName = "K2_Project";
            sqlBulk.WriteToServer(dReader);
            excelConnection.Close();
        }

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    我认为唯一的方法是遍历你的两个sheets

    看看This 的帖子。这将帮助您获得sheet 名称。

    当您拥有sheet 名称后,您可以循环访问它们,然后将它们加载到SQL

    也许这可以帮助你:

    OleDbConnection objConn = null;
    System.Data.DataTable dt = null;
    string excelConnection = "";
    
    if(strFile.Trim().EndsWith(".xlsx"))
    {
        excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
    }
    else if(strFile.Trim().EndsWith(".xls")) 
    {
        excelConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
    }
    
    objConn = new OleDbConnection(excelConnection);
    
    objConn.Open();
    
    dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    
    String[] excelSheets = new String[dt.Rows.Count];
    int i = 0;
    
    foreach(DataRow row in dt.Rows)
    {
        excelSheets[i] = row["TABLE_NAME"].ToString();
        i++;
    }
    
    for(int j=0; j < excelSheets.Length; j++)
    {
        OleDbCommand cmd = new OleDbCommand("Select * from " + excelSheets[j], excelConnection);
    
        excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
    
        sqlBulk.DestinationTableName = "YourDestinationTableName";
    
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();
    }
    

    注意:未经测试

    【讨论】:

      【解决方案2】:
      public void importdatafromexcel(string excelfilepath)
              {
                  //declare variables - edit these based on your particular situation
                  string ssqltable = "test_data";//sql table name
                  // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if havedifferent
                  string myexceldataquery = "select * from [Sheet1$]";
                  try
                  {
                      //create our connection strings
                      string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath + ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
                      string ssqlconnectionstring = "server=ServerName;user id=sa;password=sa;database=Databasename;connection reset=false";
                      //execute a query to erase any previous data from our destination table
                      string sclearsql = "Delete from " + ssqltable;
                      SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
                      SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
                      sqlconn.Open();
                      sqlcmd.ExecuteNonQuery();
                      sqlconn.Close();
                      //series of commands to bulk copy data from the excel file into our sql table
                      OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
                      OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
                      oledbconn.Open();
                      OleDbDataReader dr = oledbcmd.ExecuteReader();
                      SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
                      DataTable dt = new DataTable();
      
                      bulkcopy.DestinationTableName = ssqltable;
                      bulkcopy.WriteToServer(dr);
                      oledbconn.Close();
      
                  }
                  catch (Exception)
                  {
                      throw;
                  }
              }
      
      
      
      /*---------- call that file on buttonclick through OpenDialogBox--------*/
      
        private void button1_Click(object sender, EventArgs e)
              {
                  DialogResult result = openFileDialog1.ShowDialog();
      
                  if (result == DialogResult.OK) // Test result.
                  {
                      string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
                      importdatafromexcel(strfilename);
      
                  }
      
                  Console.WriteLine(result);
                  MessageBox.Show("Exported to SQL successfully");
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        • 2011-11-22
        • 1970-01-01
        • 2015-03-08
        • 2019-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多