0

我有一个 Excel 表,我正在使用 sqlbulkcopy 将其上传到 sqlserver 表,我在数据库表上应用了一个索引,以便忽略重复的条目,但我也想显示在网格视图中被忽略的重复条目。

  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 table2.Field<int>("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();

错误:指定的强制转换无效。table1.Field("ID") 等于 table2.Field("ID")

4

1 回答 1

0

您的一个表中的 ID 字段似乎不是 int。

与其一个或两个人猜测,不如尝试检查两个表(oltlb 和 dt4)中第一列的数据类型,看看哪个具有非整数数据类型。实际上可能两者兼而有之。

事情是这样的:即使字符串的值是数字文字,也不能将字符串强制转换为 int。您必须使用Int32.ParseConvert.ToInt32转换。因此,如果您的一个表的 ID 列具有字符串类型,您可以这样表示:

table1.Field<int>("ID") equals Convert.ToInt32(table2.Field<string>("ID"))

如果两个表都有一个字符串 ID 字段,你可以这样表达:

table1.Field<string>("ID") equals table2.Field<string>("ID")
于 2012-10-25T17:16:29.727 回答