Import Excel Spreadsheet into DataGrid

|

Originally found at http://blueraiden.exofire.net/blog/import-excel-spreadsheet-data-to-datagridview-using-vb-net

For the code to work you need to first add a DataGridView and a Button in design view and have a valid file path for the Excel file.

Imports System.Data.SqlClient

Public Class Form1

	Dim MyConnection As System.Data.OleDb.OleDbConnection
	Dim ExcelDataSet As System.Data.DataSet
	Dim ExcelAdapter As System.Data.OleDb.OleDbDataAdapter

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:/temp/contacts.xlsx;Extended Properties=Excel 12.0;")
		Try
			ExcelAdapter = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
			ExcelAdapter.TableMappings.Add("Table", "Excel Data")
			ExcelDataSet = New System.Data.DataSet
			ExcelAdapter.Fill(ExcelDataSet)
			DataGridView1.DataSource = ExcelDataSet.Tables(0)
			MyConnection.Close()
		Catch ex As Exception
			MessageBox.Show("Error: " + ex.ToString, "Importing Excel", MessageBoxButtons.OK, MessageBoxIcon.Error)
		End Try
End Sub
End Class
Originally Posted on March 25, 2013
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.