Click here to Skip to main content
16,016,759 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


To Export DataGridView Values in Excel, Powerpoint and Word format using vb.net 2.0 web form.
Posted

Hi,
VB
Imports System
Imports System.IO
Imports System.Math
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.HttpResponse
Imports System.Web.HttpRequest
Imports System.Web.HttpServerUtility
Imports System.Web.SessionState
Imports System.Collections
Imports System.Collections.Generic

Protected Sub btn_excel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_excel.Click
       If gv.Rows.Count <= 0 Then
           MsgBox(Me, "Please check your record")
           Exit Sub
       End If
       XlExport("position.ppt", Me.gv)
   End Sub

  Private Sub XlExport(ByVal fileName As String, ByVal gv1 As GridView)
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/ms-powerpoint"
        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        'create a form to contain the grid
        Dim table As Table = New Table
        table.GridLines = gv1.GridLines
        ' Collect the indexes of the columns that are set visible but make sure to obtain them
        ' in reverse order to prevent problems with shifting indexes
        Dim cellsToRemove As New List(Of Integer)
        For iCellIndex As Integer = gv1.Columns.Count - 1 To 0 Step -1
            Dim col As DataControlField = gv1.Columns(iCellIndex)
            If Not col.Visible Then cellsToRemove.Add(iCellIndex)
        Next

        ' Remove the hidden column cells from the header and footer rows if they exist

        For iCellIndex As Integer = 0 To cellsToRemove.Count - 1
            If gv1.HeaderRow IsNot Nothing Then gv1.HeaderRow.Cells.RemoveAt(cellsToRemove.Item(iCellIndex))
            If gv1.FooterRow IsNot Nothing Then gv1.FooterRow.Cells.RemoveAt(cellsToRemove.Item(iCellIndex))
        Next

        ' add the header row to the table
        If (Not (gv1.HeaderRow) Is Nothing) Then
            PrepareControlForExport(gv1.HeaderRow)
            table.Rows.Add(gv1.HeaderRow)
        End If

        ' add each of the data rows to the table
        For Each row As GridViewRow In gv1.Rows
            For iCellIndex As Integer = 0 To cellsToRemove.Count - 1
                row.Cells.RemoveAt(cellsToRemove.Item(iCellIndex))
            Next
            PrepareControlForExport(row)
            table.Rows.Add(row)
        Next
        ' add the footer row to the table
        If (Not (gv1.FooterRow) Is Nothing) Then
            PrepareControlForExport(gv1.FooterRow)
            table.Rows.Add(gv1.FooterRow)
        End If
        ' render the table into the htmlwriter
        table.RenderControl(htw)
        ' render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString)
        HttpContext.Current.Response.End()
    End Sub

   ' Replace any of the contained controls with literals
   Private Sub PrepareControlForExport(ByVal control As Control)
       Dim i As Integer = 0
       Do While (i < control.Controls.Count)
           Dim current As Control = control.Controls(i)
           If (TypeOf current Is LinkButton) Then
               control.Controls.Remove(current)
               If CType(current, LinkButton).Visible Then control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
           ElseIf (TypeOf current Is Label) Then
               control.Controls.Remove(current)
               If CType(current, Label).Visible Then control.Controls.AddAt(i, New LiteralControl(CType(current, Label).Text))
           ElseIf (TypeOf current Is ImageButton) Then
               control.Controls.Remove(current)
               control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
           ElseIf (TypeOf current Is HyperLink) Then
               control.Controls.Remove(current)
               control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
           ElseIf (TypeOf current Is DropDownList) Then
               control.Controls.Remove(current)
               control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
           ElseIf (TypeOf current Is CheckBox) Then
               control.Controls.Remove(current)
               control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
           End If
           If current.HasControls Then PrepareControlForExport(current)
           i = (i + 1)
       Loop
   End Sub
 
Share this answer
 
v2
if your gridview is showing data from a existing ms access database then the below can export it to an excel file

Sub ExportToExcelFromAccess()

Dim AccessConn As System.Data.OleDb.OleDbConnection
Dim AccessCommand As OleDbCommand
Dim xl As Excel.Application
Try
xl = GetObject(, "Excel.Application")
Catch ex As Exception
xl = New Excel.Application
End Try

Dim filepath As String
AccessConn = New System.Data.OleDb.OleDbConnection(constr)
xl.Visible = False
xl.DisplayAlerts = False
filepath = "D:\myexcelfile.xls"

Dim myfile As New FileInfo(filepath)
If myfile.Exists Then
myfile.Delete()
End If
myfile = Nothing

Try

AccessCommand = New OleDbCommand("SELECT * INTO [Excel 8.0;DATABASE=" + filepath + ";HDR=NO;].[table1] from [DB_name]", AccessConn)
AccessConn.Open()
retval = AccessCommand.ExecuteNonQuery()

Catch ex As Exception
Label5.Text = ex.Message.ToString
Finally
xl.Visible = True
xl.DisplayAlerts = True
xl.Quit()
AccessConn.Close()
AccessConn = Nothing

End Try
Label5.Text = " Click here to download"
end sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900