来自Sql Server的列数据未与Datatable中的列匹配

时间:2019-01-28 06:44:14

标签: c# sql-server excel epplus

导入Excel文件后,InvtID中的数据已经与“ 3”列匹配,但是问题如图所示,为什么最后一列数据之后的数据表中的数据列(InvtID)填充了?如何固定位置以与“ 3”列匹配。我已经将InvtID列设置为0。是否有任何一行代码可以将行开始定位为1 ?:

program

public void filldatagridview(ExcelWorksheet workSheet)
{
    DataTable dt = new DataTable();

    //Create the data column
    for (int col = workSheet.Dimension.Start.Column; 
        col <= workSheet.Dimension.End.Column; col++)
    {
        dt.Columns.Add(col.ToString());
    }

    for (int row = 12; row <= 26; row++)
    {
        DataRow newRow = dt.NewRow(); //Create a row
        int i = 0;
        for (int col = workSheet.Dimension.Start.Column; 
            col <= workSheet.Dimension.End.Column; col++)
        {
             newRow[i++] = workSheet.Cells[row, col].Text;
        }
        dt.Rows.Add(newRow);                   
    }

    dt.Columns.RemoveAt(0); //remove No 
    dt.Columns.RemoveAt(0); //remove article

    //Get BookCode 
    var barCodes = dt.AsEnumerable().Select(r => r.Field<string>("3"))
        .ToArray(); //EAN column
    var barCodesstring = string.Format("'{0}'", string.Join("','", barCodes));
    SqlCommand cmd = new SqlCommand("SELECT InvtID FROM InventoryCustomer WHERE 
        Barcode IN (" + barCodesstring + ")", conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    dt.Columns["InvtID"].SetOrdinal(0);
    dataGridView2.DataSource = dt;

    conn.Close();
}

1 个答案:

答案 0 :(得分:1)

此代码总是添加新行DataRow newRow = dt.NewRow();,因此您的行不匹配:

for (int row = 12; row <= 26; row++)
{
    DataRow newRow = dt.NewRow(); //Create a row
    //...
    dt.Rows.Add(newRow);                   
}

但是,如果我理解正确,您希望将数据设置到特定的数据单元中。然后,您应该找到现有行并设置单元格值:

DataRow dr = dt.Rows[yourRowNumber];
dr[3] = "Your New Value";