Ahmet Taha

Ahmet Taha

  • NA
  • 381
  • 20.3k

cannot import excel to datagridview in c#

May 28 2021 7:33 AM
hello guyz i need your help, i cannot import excel to datagridview in c#.net even though I add a reference using Microsoft.Office.Interlop.Excel , I m using a visual studio 2010 and this is my source code
  1. private void button1_Click(object sender, EventArgs e)    
  2. {    
  3.     _Application importExcelToDataGridViewAppl;    
  4.     _Workbook importExcelToDataGridViewWorkbook;    
  5.     _Worksheet importExcelToDataGridViewWorksheet;    
  6.     Range importExcelToDataGridViewRange;    
  7.     try    
  8.     {    
  9.         importExcelToDataGridViewAppl = new Microsoft.Office.Interop.Excel.Application();    
  10.         OpenFileDialog importExcelToDataGridViewFileDialog = new OpenFileDialog();    
  11.         importExcelToDataGridViewFileDialog.Title= "yahoo";    
  12.         importExcelToDataGridViewFileDialog.Filter = "Choose Excel File | *.xlsx;*.xls;*.xlsm";    
  13.        // importExcelToDataGridViewFileDialog.Title = "Import Excel File";    
  14.         if (importExcelToDataGridViewFileDialog.ShowDialog() == DialogResult.OK)    
  15.         {    
  16.             importExcelToDataGridViewWorkbook = importExcelToDataGridViewAppl.Workbooks.Open(importExcelToDataGridViewFileDialog.FileName);    
  17.             importExcelToDataGridViewWorksheet = importExcelToDataGridViewWorkbook.ActiveSheet;    
  18.             importExcelToDataGridViewRange = importExcelToDataGridViewWorksheet.UsedRange;    
  19.   
  20.             //    
  21.             for (int excelWorkSheetRowIndex=0;excelWorkSheetRowIndex < importExcelToDataGridViewRange.Rows.Count; excelWorkSheetRowIndex++)    
  22.             {    
  23.                 dataGridView1.Rows.Add(importExcelToDataGridViewWorksheet.Cells[excelWorkSheetRowIndex,1].Value,);    
  24.   
  25.             }    
  26.   
  27.         }    
  28.     }    
  29.     catch (Exception ex)    
  30.     {    
  31.     }    
  32.     finally    
  33.     {    
  34.     }    
  35.   
  36. }

Answers (3)