自动在同一目录和相同文件名中复制Excel文件

时间:2016-06-15 11:12:27

标签: c# sql excel winforms

我尝试使用c#导入Excel文件。当我尝试导入Excel文件时,正在创建一个具有相同名称导入文件的新Excel文件,同时新文件也已损坏。我不知道为什么会这样。 我的代码:

 private void button1_Click(object sender, EventArgs e)
    {
        //database name
        string table = "importing";
        // Excel sheet name
        string excelQuery = "select * from [Sheet1$]";
        try
        {
            //create  connection strings
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\New folder (2)\\importing1.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";";
            string sqlConnectionstring = "Data Source=LAB-2\\SQLEXPRESS;Initial Catalog=LMS;Persist Security Info=True;User ID=smart;Password=smart";
            //To clear the previous data in the database
            string resetQuery = "delete from " + table;
            SqlConnection connection = new SqlConnection(sqlConnectionstring);
            SqlCommand cmd = new SqlCommand(resetQuery, connection);
            connection.Open();
            cmd.ExecuteNonQuery();
            connection.Close();
            //copy data from the excel file 
            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmdOLEDB = new OleDbCommand(excelQuery, con);
             con.Open();
             OleDbDataReader dataReader = cmdOLEDB.ExecuteReader();
            SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlConnectionstring);
            bulkcopy.DestinationTableName = table;
            while (dataReader.Read())
            {
                bulkcopy.WriteToServer(dataReader);
            }

            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }          
    }

0 个答案:

没有答案