Exporting gridview into excel
Hi!
I have another problem here. I need to export the details in my gridview into an excel file. However, I would like this to be done in the background. I have searched and tried alot of codes online, however, almost all of them requires the user to confirm whether they want to save or open. I need it to save in the background without them even knowing that the excel is save there. The codes that I have now are as below:
Protected Sub lblFind_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim selectedDate As DateTime
Dim selectedCompany As String
selectedDate = ddlDateCreated.SelectedValue
selectedCompany = ddlCompany.SelectedValue.ToString
Dim dbconn As OleDbConnection
Dim sql As String
Dim dbcomm As OleDbCommand
Dim dataAdap As OleDbDataAdapter
Dim ds As DataSet
dbconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("App_Data/DB.mdb"))
dbconn.Open()
sql = "SELECT number, dNo, FullName, acct, passwd, cost FROM table WHERE o LIKE '" + selectedCompany + "%'" + " and DateCreated LIKE '" + selectedDate + "%'"
dbcomm = New OleDbCommand(sql, dbconn)
dataAdap = New OleDbDataAdapter(dbcomm)
ds = New DataSet
Try
Dim totnumrecs As Integer = dataAdap.Fill(ds)
If totnumrecs > 0 Then
lblEmailTo.Visible = True
ddlEmailTo.Visible = True
cmdSend.Visible = True
lblRemarks.Visible = True
txtRemarks.Visible = True
GridView1.DataSource = ds
GridView1.DataBind()
Else
lblEmailTo.Visible = False
ddlEmailTo.Visible = False
cmdSend.Visible = False
lblRemarks.Visible = False
txtRemarks.Visible = False
End If
Catch ex As Exception
lblEmailTo.Visible = False
ddlEmailTo.Visible = False
cmdSend.Visible = False
MsgBox("No records found for " + selectedCompany + " and of date " + selectedDate, MsgBoxStyle.OkOnly, "No Records Found")
End Try
End Sub
Protected Sub cmdSend_Click(ByVal sender As Object, ByVal e As System.EventArgs)
GridView1.AllowPaging = "False"
GridView1.DataBind()
Dim tw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=tryingexcel.xls")
Response.Charset = ""
EnableViewState = True
Controls.Add(frm)
frm.Controls.Add(GridView1)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
GridView1.AllowPaging = "True"
GridView1.DataBind()
End Sub
the problem here is that what my excel have saved is not the details of the data, instead it saved:
<form name="ctl01" method="post" action="try.aspx" id="ctl01">
<div>
<input type="hidden" name="__VIEWSTATE" id="
__VIEWSTATE" value="" />
</div>
<div>
</div></form>
I do not understand where's my error. I tried understanding the codes, however, I must admit that some of the codes in cmdSend, I don't really understand. Please help.
Thank you!
|