How to Read From Text File Into Datagridview
In this tutorial, I will testify you lot how to import an excel file to a DataGridview using C#. We are going to exist usingMicrosoft.Office.interop.Excel namespace in this project. There are many means to read an excel file in C#, simply this is the piece of cake manner I found for beginners like me. But follow the steps below.
Before we start, make sure that you have Visual Studio installed on your car. If not, you can visit this download link. You can download the community version for free.
Allow'southward Start:
- Beginning, Create a new Windows forma projection. Navigate to File. Choose New option. Select Project.
ii. From the New Project window. Name your project in any way you desire. In my example, I name my projection Upload_Data_From_Excel. Proceed on clicking the "Ok" button. Run into the image below.
3. Add controls from the toolbox. What we need is a Grade, buttons, and OpenFileDialog.
- Form
- Button -> for the upload click event.
- OpenFileDialog -> for browsing files.
- DataGridview ->for viewing of information
Below paradigm is the UI I created. This volition help you visualize and understand the next stride.
- For clarity and easy navigating, we will rename our push button. Click the button you added to your class and go to its property from the solution explorer and change the value. In my case, I name it as btn_Upload.
v. Now navigate to your solution explorer and correct-click on Reference, choose Add Reference, and then addMicrosoft.Part.Interop.Excel.
6. From the reference manager window, aggrandize Assemblies,and click Extensions from the left pane and search forMicrosoft.Office.Interop.Excelfrom the eye pane.
7. Verify if the reference is added. Go to your project solution explorer. Aggrandize Reference,so await forMicrosoft.Office.Interop.Excel.
8. After we verify and successfully added Microsoft.Part.Interop.Excel. Open your form blueprint and double click on the btn_Uploadbutton to add push button click event.
9. Copy and paste the lawmaking below to yourbtn_Upload Click Event.
cord file = ""; //variable for the Excel File Location DataTable dt = new DataTable(); //container for our excel data DataRow row; DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Cheque if Result == "OK". { file = openFileDialog1.FileName; //go the filename with the location of the file try { //Create Object for Microsoft.Role.Interop.Excel that will be use to read excel file Microsoft.Role.Interop.Excel.Awarding excelApp = new Microsoft.Part.Interop.Excel.Awarding(); Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file); Microsoft.Function.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[ane]; Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange; int rowCount = excelRange.Rows.Count; //go row count of excel information int colCount = excelRange.Columns.Count; // get column count of excel data //Get the showtime Column of excel file which is the Column Name for (int i = one; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString()); } intermission; } //Get Row Information of Excel int rowCounter; //This variable is used for row index number for (int i = ii; i <= rowCount; i++) //Loop for available row of excel data { row = dt.NewRow(); //assign new row to DataTable rowCounter = 0; for (int j = 1; j <= colCount; j++) //Loop for available column of excel data { //check if cell is empty if (excelRange.Cells[i, j] != nothing && excelRange.Cells[i, j].Value2 != null) { row[rowCounter] = excelRange.Cells[i, j].Value2.ToString(); } else { row[i] = ""; } rowCounter++; } dt.Rows.Add(row); //add row to DataTable } dataGridView1.DataSource = dt; //assign DataTable as Datasource for DataGridview //close and clean excel process GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.ReleaseComObject(excelRange); Marshal.ReleaseComObject(excelWorksheet); //quit apps excelWorkbook.Close(); Marshal.ReleaseComObject(excelWorkbook); excelApp.Quit(); Marshal.ReleaseComObject(excelApp); } catch(Exception ex) { MessageBox.Show(ex.Message); }
- Now you are prepare to run your project and exam if no mistake occurs. Run your awarding past pressing ctrl + f5 without debugging or f5 for debugging style.
- Click Upload button to upload.
- So select your excel file. See the image below.
This is how to Import Excel to Datagridview using C# code. Hopes this helps.
Final output:
Excel File:
Project Output:
Full Lawmaking:
using Arrangement; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Cartoon; using System.IO; using Organization.Linq; using Arrangement.Runtime.InteropServices; using System.Text; using Organisation.Threading.Tasks; using System.Windows.Forms; namespace Upload_Data_From_Excel { public partial class Upload_Data_Frm_EXCEL : Form { public Upload_Data_Frm_EXCEL() { InitializeComponent(); } individual void btn_upload_Click(object sender, EventArgs east) { string file = ""; //variable for the Excel File Location DataTable dt = new DataTable(); //container for our excel information DataRow row; DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Check if Result == "OK". { file = openFileDialog1.FileName; //go the filename with the location of the file endeavor { //Create Object for Microsoft.Office.Interop.Excel that volition be use to read excel file Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Role.Interop.Excel.Application(); Microsoft.Part.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file); Microsoft.Role.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1]; Microsoft.Part.Interop.Excel.Range excelRange = excelWorksheet.UsedRange; int rowCount = excelRange.Rows.Count; //get row count of excel data int colCount = excelRange.Columns.Count; // get column count of excel data //Become the first Cavalcade of excel file which is the Column Name for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString()); } suspension; } //Get Row Information of Excel int rowCounter; //This variable is used for row alphabetize number for (int i = 2; i <= rowCount; i++) //Loop for available row of excel data { row = dt.NewRow(); //assign new row to DataTable rowCounter = 0; for (int j = ane; j <= colCount; j++) //Loop for available column of excel data { //check if cell is empty if (excelRange.Cells[i, j] != zilch && excelRange.Cells[i, j].Value2 != cipher) { row[rowCounter] = excelRange.Cells[i, j].Value2.ToString(); } else { row[i] = ""; } rowCounter++; } dt.Rows.Add(row); //add row to DataTable } dataGridView1.DataSource = dt; //assign DataTable as Datasource for DataGridview //Close and Clean excel process GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.ReleaseComObject(excelRange); Marshal.ReleaseComObject(excelWorksheet); excelWorkbook.Close(); Marshal.ReleaseComObject(excelWorkbook); //quit excelApp.Quit(); Marshal.ReleaseComObject(excelApp); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } }
Thank you for reading! Happy Coding!!
If you are interested in ASP.Cyberspace Core you may visit my Blog page for my latest post.
As well Read: Ethernut telecommunication
Source: https://www.freecodespot.com/blog/csharp-import-excel/
0 Response to "How to Read From Text File Into Datagridview"
Post a Comment