473,386 Members | 1,733 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,386 developers and data experts.

Reading Data From Excelsheet in DataGridView

This code will read data from excelsheet in gridview......take a submit button and take a datagrid....and use below code...its works fine....


Expand|Select|Wrap|Line Numbers
  1. private void btnsubmit_Click(object sender, EventArgs e)
  2.         {
  3.  
  4.                 Excel.Application appExl;
  5.                 Excel.Workbook workbook;
  6.                 Excel.Worksheet NwSheet;
  7.                 Excel.Range ShtRange;
  8.                 appExl = new Excel.ApplicationClass();
  9.                 workbook = appExl.Workbooks.Open(("C:\\data.xlsx"), Missing.Value, Missing.Value,
  10.                     Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
  11.                     Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
  12.                 NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
  13.  
  14.                 int Cnum = 0;
  15.                 int Rnum = 0;
  16.  
  17.                 ShtRange = NwSheet.UsedRange;
  18.                 DataTable dt = new DataTable();
  19.                 dt.Columns.Add("name");
  20.                 dt.Columns.Add("address");
  21.                // dt.Columns.Add("Status");
  22.                 dt.Columns.Add("Phone");
  23.                 for (Rnum = 1; Rnum <= ShtRange.Rows.Count; Rnum++)
  24.                 {
  25.                     DataRow dr = dt.NewRow();
  26.                     for (Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
  27.                     {
  28.                         dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
  29.                     }
  30.                     dt.Rows.Add(dr);
  31.                     dt.AcceptChanges();
  32.                 }
  33.                 workbook.Close(true, Missing.Value, Missing.Value);
  34.                 appExl.Quit();
  35.  
  36.  
  37.                 //Session["data"] = dt;
  38.                 dataGridView1 .DataSource = dt;
  39.                 //dataGridView1.DataBind();
  40.  
  41.             }
Nov 21 '11 #1
3 17070
hi buddy.. yours code works good.. U r awesome.. But i need to know one more thing.. pls help.. how to display contents of different sheets in excel file.. for example my excel file contains sheet1,sheet2,sheet3.. i need to display contents of any sheet i want by selecting the desired sheet.
May 13 '15 #2
SioSio
272 256MB
This code can select a sheet.
Set two buttons, one Combobox and one DatagridView on the form.
Click Button1 to set the sheet name of the excel file in the Combobox1.
Select a sheet from the combobox1 and click Button2, and the values of the selected sheet will be displayed in the DatagridView.
Expand|Select|Wrap|Line Numbers
  1. public static class Global
  2.     {
  3.         public static string excelName;
  4.     }
  5.     public partial class MainForm : Form
  6.     {
  7.         public MainForm()
  8.         {
  9.             InitializeComponent();
  10.             Global.excelName = System.AppDomain.CurrentDomain.BaseDirectory + "\\sample.xlsx";
  11.             dataGridView1.AutoGenerateColumns = false;
  12.         }
  13.  
  14.         void Button1Click(object sender, EventArgs e)
  15.         {
  16.             Excel.Application mExcel;
  17.             mExcel = new Excel.Application();
  18.             try
  19.             {
  20.                 Excel.Workbook mWorkbook;
  21.                 mExcel.Visible =false;
  22.                 // excel open
  23.                 mWorkbook = (Excel.Workbook)(mExcel.Workbooks.Open(
  24.                     Global.excelName
  25.                 ));
  26.                 try
  27.                 {
  28.                     foreach (Microsoft.Office.Interop.Excel.Worksheet sh in mWorkbook.Sheets)
  29.                     {
  30.                         //ComboBox
  31.                         comboBox1.Items.Add(sh.Name);
  32.                     }
  33.                     comboBox1.SelectedIndex = 0;
  34.                 }
  35.                 finally
  36.                 {
  37.                     // close book
  38.                     mWorkbook.Close(false);
  39.                     System.Runtime.InteropServices.Marshal.ReleaseComObject(mWorkbook);
  40.                 }
  41.             }
  42.             finally
  43.             {
  44.                 if (null != mExcel)
  45.                 {
  46.                     try
  47.                     {
  48.                         mExcel.DisplayAlerts = false;
  49.                         mExcel.Quit();
  50.                     }
  51.                     finally
  52.                     {
  53.                         System.Runtime.InteropServices.Marshal.ReleaseComObject(mExcel);
  54.                     }
  55.                 }
  56.             }
  57.         }
  58.  
  59.         // set to datagridview from excel sheet
  60.         void Button2Click(object sender, EventArgs e)
  61.         {
  62.             // application object
  63.             Excel.Application mExcel;
  64.             // create instance
  65.             mExcel = new Excel.Application();
  66.             try
  67.             {
  68.                 // book object
  69.                 Excel.Workbook mWorkbook;
  70.                 // No display Excel
  71.                 mExcel.Visible = false;
  72.                 // open
  73.                 mWorkbook = (Excel.Workbook)(mExcel.Workbooks.Open(
  74.                     Global.excelName
  75.                 ));
  76.                 try
  77.                 {
  78.                     Excel.Worksheet SheetSample; // Worksheet object
  79.                     SheetSample = (Excel.Worksheet)mWorkbook.Sheets[comboBox1.SelectedIndex+1];
  80.                     try
  81.                     {
  82.                         var rowCount = SheetSample.UsedRange.Rows.Count;
  83.                         var columnCount = SheetSample.UsedRange.Columns.Count;
  84.                         dataGridView1.ColumnCount = columnCount;
  85.                         Microsoft.Office.Interop.Excel.Range xlCells = null;
  86.                         Microsoft.Office.Interop.Excel.Range xlRange = null;
  87.                         xlCells = SheetSample.Cells;
  88.                         try
  89.                         {
  90.                             for(int c = 1; c <= columnCount; c++)
  91.                             {
  92.                                 xlRange = (Microsoft.Office.Interop.Excel.Range)xlCells[1, c];
  93.                                 dataGridView1.Columns[c-1].HeaderText = Convert.ToString(xlRange.Value2);
  94.                             }
  95.                             for(int r = 2; r <= rowCount; r++)
  96.                             {
  97.                                 string[] stringArray = new string[columnCount];
  98.                                 for(int c = 1; c <= columnCount; c++)
  99.                                 {
  100.                                     xlRange = (Microsoft.Office.Interop.Excel.Range)xlCells[r, c];
  101.                                     stringArray[c-1] = Convert.ToString(xlRange.Value2);
  102.                                 }
  103.                                 dataGridView1.Rows.Add(stringArray);
  104.                             }
  105.                         }
  106.                         finally
  107.                         {
  108.                             System.Runtime.InteropServices.Marshal.ReleaseComObject(xlCells);
  109.                             System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange);
  110.                         }
  111.                     }
  112.                     finally
  113.                     {
  114.                         System.Runtime.InteropServices.Marshal.ReleaseComObject(SheetSample);
  115.                     }
  116.                 }
  117.                 finally
  118.                 {
  119.                     // close the book
  120.                     mWorkbook.Close(false);
  121.                     System.Runtime.InteropServices.Marshal.ReleaseComObject(mWorkbook);
  122.                 }
  123.             }
  124.             finally
  125.             {
  126.                 if (null != mExcel)
  127.                 {
  128.                     try
  129.                     {
  130.                         mExcel.DisplayAlerts = false;
  131.                         mExcel.Quit();
  132.                     }
  133.                     finally
  134.                     {
  135.                         System.Runtime.InteropServices.Marshal.ReleaseComObject(mExcel);
  136.                     }
  137.                 }
  138.             }
  139.         }
  140.     }
Jun 25 '21 #3
Cezar
3 2Bits
I used Spire.XLS for .NET to expert data from Excel sheet to DataGridView, and it worked like a charm.

Compared with Microsoft.Office.Interop.Excel, the biggest advantage of Spire.XLS is that there is no need to installed MS Office on computers.

Expand|Select|Wrap|Line Numbers
  1. //Create a new workbook
  2. Workbook workbook = new Workbook();       
  3. //Load an excel file
  4. workbook.LoadFromFile(@”C:\Users\Administrator\Desktop\data.xlsx”);          
  5. //Get the first worksheet
  6. Worksheet sheet = workbook.Worksheets[0];
  7. //Export data from excel to datagridview 
  8. this.dataGridView1.DataSource = sheet.ExportDataTable();
  9.  
Jan 12 '22 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Dariusz | last post by:
Below is part of a code I have for a database. While the database table is created correctly (if it doesn't exist), and data is input correctly into the database when executed, I have a problem...
0
by: Andy | last post by:
Hi, In the code below (not pretty I know but it's an early version :-P) I'm having problems reading the data object back in. If I move the reading code to immediately after the section where it...
1
by: Magnus | last post by:
allrite folks, got some questions here... 1) LAY-OUT OF REPORTS How is it possible to fundamentaly change the lay-out/form of a report in access? I dont really know it that "difficult", but...
3
by: abc my vclass | last post by:
There are some programs written on .NET 1.1. These applications are apply n-tiers contains Data Access Layers or Business Logic Layer. Now, our company upgrade to .NET 2.0 and enhance or rewrite...
1
by: ashik478 | last post by:
Hi! I have a problem. I have a table in oracle database with one field is primary key. Now I want to insert data from Datagridview with hide column which contain not null field(this field is...
14
by: wassssup | last post by:
hi guys..im new to datagridview and im wondering is there a way to convert an encrypted data in access and show it in a datagridview? im using C# and microsoft access normally this is how to show...
4
by: shripal | last post by:
hello, i am new to c#.net. i have imported data in datagridview form ms access database. now i want to store each row of datagridview saperatly in string array so in saperate class i...
1
by: progvar | last post by:
Hi i want to update data in database using datagridview actually i am displaying the data in datagridview and after that i want to update some rows data directly modifying the displayed data into...
0
by: premMS143 | last post by:
Hi, I have created application using VB.net & backend MS Access. During run time I add certain rows of data to Datagridview. After finalizing it I want to update those data present in datagridview...
0
by: Arnold Agolli | last post by:
Hello! Can sb explain me how to connect to a .accdb database and on Form_Load to display its data in DataGridView!(i want this in odbc because in oledb it didnt work because im using 64-bit windows...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.