无法将类型为“System.Double”的对象强制转换为“System.String”。

时间:2012-10-26 04:29:11

标签: c# asp.net sql sql-server linq

我正在将excel数据导入到sql表中,同时我想在网格视图中显示excel表和sql表中的重复行以下是我的尝试:

  protected void Button1_Click(object sender, EventArgs e)
{
    string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
    string strFileName = FileUpload1.PostedFile.FileName.ToString();

    FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
    string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);






        string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");

    //string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;"); 


        // Create Connection to Excel Workbook
        using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
            OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]", connection);

            //Sql Server Table DataTable
            DataTable dt4 = new DataTable();
            SqlCommand cmd4 = new SqlCommand("select id,data from ExcelTable", con);
            try
            {
                SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
                da4.Fill(dt4);//sql table datatable
            }
            catch { }


            //excelsheet datatable
            DataTable oltlb = new DataTable();
            OleDbCommand olcmd = new OleDbCommand("select id,data from [Sheet1$]", connection);
            try
            {
                OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
                olda.Fill(oltlb); //excel table datatable
            }
            catch { }

            var matched = (from table1 in dt4.AsEnumerable()
                           join table2 in oltlb.AsEnumerable() on
                         table1.Field<int>("ID") equals Convert.ToInt32(table2.Field<string>("ID"))
                           where table1.Field<string>("Data") == table2.Field<string>("Data")
                           select table1);
            DataTable dthi5 = new DataTable();
            dthi5 = matched.CopyToDataTable();

            GridView1.DataSource = dthi5;
            GridView1.DataBind();
            GridView1.DataSource = matched.ToList();

Id是int(允许空值),sql server数据库中的数据(nvarchar)

0 个答案:

没有答案