Hey,,I tried the following code to retrieve data from an excel file,apply query and save the result of query to another excel file.
Now there are two problems:
One,I am getting the required data but some reduntant unwanted data too.
Second,It only works if the excel file, from which the data is retrieved, is open.
Help me out.
Dim dr As OleDbDataReader
Dim i As Integer
Dim strLine As String = ""
Dim fileExcel As String
Dim objFileStream As FileStream
Dim objStreamWriter As StreamWriter
Dim MyCommand As OleDbCommand
Dim MyConnection As System.Data.OleDb.OleDbConnection
MyConnection = New System.Data.OleDb.OleDbConnection( _
"provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source= C:\Users\Space Era\Documents\Book1.xlsx ; " & _
"Extended Properties=Excel 8.0")
fileExcel = "c:\temp\test.xls"
'Use FileStream to create the .xls file.
objFileStream = New FileStream(fileExcel, FileMode.OpenOrCreate, FileAccess.Write)
objStreamWriter = New StreamWriter(objFileStream)
MyConnection.Open()
MyCommand = New System.Data.OleDb.OleDbCommand("select * from [Sheet1$] where [Name]='Rahul' ", MyConnection)
dr = MyCommand.ExecuteReader()
For i = 0 To dr.FieldCount - 1
If Not String.IsNullOrEmpty(strLine) Then
strLine &= ","
End If
strLine &= """" & dr.GetName(i).ToString & """"
Next
'Write the field name information to file.
objStreamWriter.WriteLine(strLine)
'Reinitialize the string for data.
strLine = ""
'Enumerate the database that is used to populate the file.
While dr.Read()
For i = 0 To dr.FieldCount - 1
strLine = strLine & dr.GetValue(i) & Chr(9)
Next
objStreamWriter.WriteLine(strLine)
strLine = ""
End While
dr.Close()
objStreamWriter.Close()
objFileStream.Close()
MyConnection.Close()