merge two excel files to dataGridView for different column name and number.
Loading
merge two excel files to dataGridView for different column name and number.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Sep 27, 2022, 2:48 AM EDT
check it
private void button1_Click(object sender, EventArgs e) { int row = 0; string[] ListFiles = Directory.GetFiles(@"C:\Users\User Name\Documents\ttt", "*.xlsx", SearchOption.AllDirectories); foreach (string filename in ListFiles) { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filename); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; dataGridView1.ColumnCount = 2; //iterate over the rows and columns and print to the console as it appears in the file //excel is not zero based!! for (int i = 1; i <= rowCount; i++) { string[] colstring = {"",""}; // two columns for (int j = 1; j <= colCount; j++) { //new line if (j == 1) Console.Write("\r\n"); //write the value to the console if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) { Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); Console.WriteLine(j); colstring[j-1] = xlRange.Cells[i, j].Value2.ToString(); } } dataGridView1.Rows.Add(colstring); } //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); // rule of thumb for releasing com objects: // never use two dots, all COM objects must be referenced and released individually // ex: [somthing].[something].[something] is bad //release com objects to fully kill excel process from running in the background Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //close and release xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //quit and release xlApp.Quit(); Marshal.ReleaseComObject(xlApp); } print_datagridview(); } private void print_datagridview() { for (int rows = 0; rows < dataGridView1.Rows.Count; rows++) { Console.Write("\n"); for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++) { if ( dataGridView1.Rows[rows].Cells[col] != null) { if ( dataGridView1.Rows[rows].Cells[col].Value != null) { string value = dataGridView1.Rows[rows].Cells[col].Value.ToString(); Console.Write(value + "\t"); } } } } }