Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

datagrid to MS-Excel 1

Status
Not open for further replies.

sthmpsn1

MIS
Sep 26, 2001
456
US
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?

Scott
 
This is from the "old school", but it still works. :)

faq216-738
penny1.gif
penny1.gif
 
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 <> &quot;&quot; Then
_FilePath = Configuration.ConfigurationSettings.GetConfig (MachineType)(&quot;ExcelFilePath&quot;)
Else
'throw exception
Throw New GenericException()
End If

filepath = _FilePath
filename = filepath & &quot;\&quot; & fileExcel

'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 = &quot;&quot;

'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 = &quot;&quot;
End While

'clean up
reader.Close()
objStreamwriter.Close()
objFileStream.Close()

Else
Exit Sub
End If

'Open the Excel File
Response.Write(&quot;<script language=javascript>window.open('&quot; & fileExcel & &quot;', '', 'width=700, height=475, left=100, top=50, location=no, menubar=yes, resizable=yes, scrollbars=yes, status=no, titlebar=yes, toolbar=no');</script>&quot;)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top