Click here to Skip to main content
15,906,301 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, I have a program that are able to import an excel file to datatable binding with datagridview. Currently I need to add another column name InvtID and get that InvtID data from sql based on Barcode column that I have been imported.

How am I able to achieve this one as right now my coding are able to get the data AFTER import an excel, so the column data are not in side-by-side with Barcode column. This is the only problem I encounter to finish this task, please help me.

What I have tried:

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
      using (SqlConnection conn = new SqlConnection("Server"))
      using (SqlCommand cmd = new SqlCommand(null, conn))
     {
    StringBuilder sb = new StringBuilder("WITH cte AS(SELECT case WHEN InvtID IS NULL OR InvtID='' THEN 'No Bookcode Found' ELSE InvtID END AS InvtID,Barcode,ROW_NUMBER() OVER(PARTITION BY Barcode ORDER BY InvtID Asc) rid FROM InventoryCustomer) SELECT InvtID AS BOOKCODE FROM cte WHERE rid=1 and Barcode In (");
             for (int i = 0; i < dt.Rows.Count; i++)
              {
                 if (i != 0) sb.Append(",");
                  string name = "@P" + i;
                  cmd.Parameters.AddWithValue(name, dt.Rows[i]["3"]); //"3" is barcode column
                  sb.Append(name);
              }
              sb.Append(") ORDER BY Barcode Asc");
              cmd.CommandText = sb.ToString();
              SqlDataAdapter da = new SqlDataAdapter(cmd);
              da.Fill(dt);

              dt.Columns["BOOKCODE"].SetOrdinal(0);
              dataGridView2.DataSource = dt;
           }
      }
Posted
Updated 6-Feb-19 20:27pm

1 solution

I'll do that this way:
1) create DataSet[^] (ds)
//Excel
2) create OleDbConnection[^] to Excel file
3) create OleDbCommand[^] to grab data from Excel
4) load data into DataTable[^] (dt1) object via OleDbDataReader[^]
5) add dt1 object to ds
//SQL Server
6) create SqlConnection[^] to SQL database
7) create SqlCommand[^] to grab data from SQL server
8) load data into DataTable (dt2) object via SqlDataReader[^]
9) add dt2 to ds
//final job
10) join data via Linq:

C#
	string sFileName = @"D:\yourExcelFile.xlsx";
	string sConStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES';", sFileName);

        string sSqlConn = "enter connection details to SQL server";
	//create dt1 and dt2 to be able to use them later
	DataTable dt1 = new DataTable();
	DataTable dt2 = new DataTable();
	
	//1.
	DataSet ds = new DataSet();
	//2.
	using (OleDbConnection connection = new OleDbConnection(sConStr))
	{
		string sql = @"SELECT * FROM [Sheet1$];";
		connection.Open();
		//3.
		using(OleDbCommand command = new OleDbCommand(sql, connection))
		{
		    //4.
                    using (OleDbDataReader reader = command.ExecuteReader())
		    {
		        dt1.Load(reader);
		    }
		}
		//5.
		ds.Tables.Add(dt1);
		//clean up
		command.Dispose();
	}

	//6.

	using (SqlConnection connection = new SqlConnection(sSqlConn))
	{
		string sql = @"SELECT * FROM YourTable";
		connection.Open();
		//7.
		using(SqlCommand command = new SqlCommand(sql, connection))
		{
		    //8.
		    using(SqlDbDataReader reader = command.ExecuteReader())
		    {
		        dt2.Load(reader);
		    }
		}
		//9.
		ds.Tables.Add(dt2);
		//clean up
		command.Dispose();
	}

//10.
var commonData = (from r1 ds.Tables("dt1").AsEnumerable()
    join r2 ds.Tables("dt1").AsEnumerable() on r1.Field<string>("Barcode") equals r1.Field<string>("Barcode"))
    .Select(x=>new
    {
        A = r1.Field<Type>("Name1"),
        B = r1.Field<Type>("Name2"),
        C = r1.Field<Type>("Name3"),
        //second datatable data 
        D = r2.Field<Type>("Name1")
    })
    .ToList();

//open Excel file and dump data into it!
foreach(var row in commonData)
{
    //your logic here...
   
}


Note: above code has been writen direct from my head, so it can contains errors.

Good luck!
 
Share this answer
 
v5
Comments
Member 14127871 7-Feb-19 2:54am    
Thank you for giving me the one-by-one steps. However, is it possible for me to stick using epplus library instead of using OleDbConnection and proceed with your steps suggestion?
Maciej Los 7-Feb-19 3:06am    
Why? What's wrong with my suggestion? Is there any particular reason to use EPPlus?
[EDIT]
You can use EPPlus library to upgrade data in Excel inside a foreach loop.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900