hi all,
i am new to vb.net programming i am trying to export data from dat grid view to the ms excel 2007 worksheet i am getting data into datagridview from an ms access 2007 database my error is :
Object reference not set to an instance of an object.
i have written export to ms excel code in Button1_Click event k
so o am giving my code below pls try to help me out.
i am new to vb.net programming i am trying to export data from dat grid view to the ms excel 2007 worksheet i am getting data into datagridview from an ms access 2007 database my error is :
Object reference not set to an instance of an object.
i have written export to ms excel code in Button1_Click event k
so o am giving my code below pls try to help me out.
VB.NET:
Imports System.Data
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.Reflection.Missing
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\USER\Desktop\D0605\ACCESSLINK1.mdb"
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\USER\Desktop\D0605\data1.accdb"
Dim SQLString As String = "SELECT Company_name, count(Company_name) as counts FROM table1 group by Company_name"
Dim OleDBConn1 As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(ConnString)
Dim DataSet1 As New DataSet()
Dim OleDbDataAdapter1 As System.Data.OleDb.OleDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQLString, OleDBConn1)
OleDBConn1.Open()
OleDbDataAdapter1.Fill(DataSet1, "table1")
DataGridView1.DataSource = DataSet1.Tables("table1")
end sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim wapp As New Microsoft.Office.Interop.Excel.Application
Dim wsheet As New Microsoft.Office.Interop.Excel.Worksheet
Dim wbook As Microsoft.Office.Interop.Excel.Workbook
wapp = New Microsoft.Office.Interop.Excel.Application
wapp.Visible = True
wsheet = Nothing
wbook = wapp.Workbooks.Add()
wsheet = wbook.ActiveSheet
Dim iX As New Integer
Dim iY As New Integer
Dim iC As Integer
For iC = 0 To DataGridView1.Columns.Count - 1
wsheet.Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
wsheet.Cells(1, iC + 1).font.bold = True
Next
wsheet.Rows(2).select()
For iX = Nothing To DataGridView1.Rows.Count - 1
For iY = Nothing To DataGridView1.Columns.Count - 1
wsheet.Cells(iX + 1, iY + 1) = DataGridView1(iY, iX).Value.ToString
'wsheet.Cells(iX + 1, iY + 1).v = DataGridView1(iY, iX).Value.ToString
Next
Next
wapp.Visible = True
wapp.UserControl = True
End Sub
End Class
Last edited by a moderator: