0

我有一个 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();
        }
4

2 回答 2

0

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

看看这篇文章。这将帮助您获取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();
}

注:未测试

于 2012-08-10T11:24:32.233 回答
0
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");
        }
于 2014-06-27T09:51:48.340 回答