How to Read an Excel file using Visual Basic.Net

0
452

In this tutorial I will teach you how to Read an excel file using visual basic.net.
This tutorial is great help for users who are having some trouble on how to Read an excel file using visual basic.net. So let’s get started:

  • First is open the Visual Basic, Select File on the menu, then click New and create a new project.

  • Then a New Project Dialog will appear. You can rename your project, depending on what you like to name it. After that click OK

  • Design your form like this just like what I’ve shown you below.
    Add a 2 Textbox and a Button

  • After designing your form. Add a reference to Microsoft Excel 12.0 Object Library
    In your project menu click on Project– Add Reference – go to COM tab

Add Microsoft Excel 12.0 Object Library

  • Then, go to the code page and add the following declarations:
  1. Imports Excel = Microsoft.Office.Interop.Excel
  2. Public Class Form1
  3. Dim APP As New Excel.Application
  4. Dim worksheet As Excel.Worksheet
  5. Dim workbook As Excel.Workbook
  6.  
  7.  

 

  • Add this following code to Form_Load Event
  1.  
  2.  
  3. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  4. workbook = APP.Workbooks.Open("C:\Users\Clive\Documents\Visual Studio 2008\clive projects\writeandread\writeandread\bin\Debug\sales.xlsx")
  5. worksheet = workbook.Worksheets("sheet1")
  6. End Sub

To get the value from Excel cell to TextBox. Add this following code to the Button Click Event.

  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  2. Handles Button1.Click
  3. TextBox1.Text = worksheet.Cells(1, 1).Value
  4. TextBox2.Text = worksheet.Cells(1, 2).Value
  5. End Sub
  6.  
  7.  

 

Then finally, add this code to save the Excel file and closes it.

  1. Private Sub Form1_FormClosed(ByVal sender As System.Object, _
  2. ByVal e As System.Windows.Forms.FormClosedEventArgs) _
  3. Handles MyBase.FormClosed
  4. workbook.Save()
  5. workbook.Close()
  6. App.Quit()
  7. End Sub
  8.  
  9.  
  • Click F5 to run the program.

If you have any questions or suggestions about How to Read an Excel file using Visual Basic.Net please contact me through our contact page.

Download How to Read an Excel file using Visual Basic.Net Source code Here

 

Readers might read also:

 

 

 

 

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here