I have a datagrid that I display on a aspx page and want the user to have the option to export that information to excel. Is there an easy way to set that up?
Dim I As Integer
Dim strLine As String, filepath, fileExcel, Link
Dim objFileStream As FileStream
Dim objStreamwriter As StreamWriter
Dim nRandom As Random = New Random(DateTime.Now.Millisecond)
Dim fs As Object, myfile As Object
'Create a random file name
fileExcel = _Id & "_" & nRandom.Next.ToString & ".xls"
'Set a Virtual Folder (I use a machine variable to identify the correct path to export to depending on the enviroment I am in)
Dim _FilePath As String
Dim MachineType As String = System.Environment.GetEnvironmentVariable("MachineType"
If Not MachineType Is Nothing Or MachineType <> "" Then
_FilePath = Configuration.ConfigurationSettings.GetConfig (MachineType)("ExcelFilePath"
Else
'throw exception
Throw New GenericException()
End If
'FileStream creates the Excel
objFileStream = New FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)
objStreamwriter = New StreamWriter(objFileStream)
'Get The Data ---You may be able to do something here with your datagid.
If SetupData() Then
Dim reader As SqlDataReader
reader = (get your data)
'Loop through the transaction
For I = 0 To reader.FieldCount - 1
strLine = strLine & reader.GetName(I).ToString & Chr(9)
Next
'write the field names out
objStreamwriter.WriteLine(strLine)
'ReInitialize the string
strLine = ""
'populate the fields
While reader.Read
For I = 0 To reader.FieldCount - 1
strLine = strLine & reader.GetValue(I) & Chr(9)
Next
objStreamwriter.WriteLine(strLine)
strLine = ""
End While
'clean up
reader.Close()
objStreamwriter.Close()
objFileStream.Close()
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.