I have the following code to export a gridview to excel and the export works just fine. The issue is that no mater what I do it names the file the name of the webform .xls instead of the name I am providing in the code (Team.xls).
Protected Sub btnExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcell.Click
Dim sw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(sw)
Dim frm As HtmlForm = New HtmlForm()
Page.Response.AddHeader("content-disposition", "attachment;Team.xls")
Page.Response.ContentType = "application/vnd.ms-excel"
Page.Response.Charset = ""
Page.EnableViewState = False
frm.Attributes("runat") = "server"
Controls.Add(frm)
frm.Controls.Add(gvTeam)
frm.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
End Sub
You have forgotten to mention filename=Team.xls
It should be "attachment;filename=Team.xls" instead of attachment;Team.xls
Related
I have a website in Asp.net wherein I have implemented a button to Store GridView in an Excel Format but when I open the file I am unable to see the actual contents of the GridView and I can only see the column headings. I have used three following imports after installing EPPlus via NuGet Package Manager.
using OfficeOpenXml;
using System.IO;
using WebFormsTest.Models;
My code behind is as follows
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Dim GetProducts As Object = Nothing
GridView6.DataSource = GetProducts
GridView6.DataBind()
End If
End Sub
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Response.Clear()
Dim products = GetProducts()
GridView6.DataSource = products
GridView6.DataBind()
Dim excel As ExcelPackage = New ExcelPackage
Dim workSheet = excel.Workbook.Worksheets.Add("Products")
Dim totalCols = GridView6.Rows(0).Cells.Count
Dim totalRows = GridView6.Rows.Count
Dim headerRow = GridView6.HeaderRow
worksheet.Cells["A1"].LoadFromCollection(GetProducts())
Dim memoryStream = New MemoryStream
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=products.xlsx")
excel.SaveAs(memoryStream)
memoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.End()
End Sub
Public Function GetProducts() As List(Of Product)
End Function
My Aspx button is as given below
<asp:Button ID="Button3" runat="server" Text="EXPORT RTD TO EXCEL" onclick="Button3_Click" BackColor="#FF9966" CssClass="btn btn-large" Font-Bold="True"/>
Editing the code behind to the following solves this problem and via the Nuget Package Manager we can download ClosedXML so that it includes the following import
Imports ClosedXML.Excel
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim dt As New DataTable("GridView_Data")
For Each cell As TableCell In GridView5.HeaderRow.Cells
dt.Columns.Add(cell.Text)
Next
For Each row As GridViewRow In GridView5.Rows
dt.Rows.Add()
For i As Integer = 0 To row.Cells.Count - 1
dt.Rows(dt.Rows.Count - 1)(i) = row.Cells(i).Text
Next
Next
Dim wb As New XLWorkbook
wb.Worksheets.Add(dt)
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;filename=GridViewPOLQA.xlsx")
Using MyMemoryStream As New MemoryStream()
wb.SaveAs(MyMemoryStream)
MyMemoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.[End]()
End Using
End Sub
I don't know what the datatype is of products, but why not bind it directly to the sheet?
worksheet.Cells["A1"].LoadFromCollection(GetProducts());
And you are not seeing the contents of the GridView on Button3_Click because you are sending an Excel file to the client (by setting the Response.ContentType), not an updated html page where the GridView has been filled with products.
Quick demo translated from C# to vb
Dim excelPackage As ExcelPackage = New ExcelPackage
Dim worksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1")
worksheet.Cells("A1").LoadFromCollection(GetProducts())
Dim bin() As Byte = excelPackage.GetAsByteArray
Response.ClearHeaders
Response.Clear
Response.Buffer = true
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-length", bin.Length.ToString)
Response.AddHeader("content-disposition", "attachment; filename=""mySheet.xlsx"""")", Response.OutputStream.Write(bin, 0, bin.Length))
Response.Flush
HttpContext.Current.ApplicationInstance.CompleteRequest
The following code is my current attempt at opening some data in excel from a website button in VB.Net. I would like the data to show up barebones, but the formatting from the table on the website always follows. The paging and colors make the data near impossible to read and can only see the first page of data. Any quick fixes? I've tried a lot of things I've found on here but to no avail.
Private Sub DownloadExcel()
Response.Clear()
'Dim dt As DataTable = TryCast(ViewState("GridData"), DataTable)
Grid_Bad_Meters.AllowPaging = False
Grid_Bad_Meters.AllowSorting = False
'Grid_Bad_Meters.DataSource = dt
'Grid_Bad_Meters.DataBind()
Dim sfile As String = "Communication_Failures" & Now.Ticks
Response.AddHeader("content-disposition", "attachment;filename=" & sfile & ".xls")
Response.Charset = ""
' If you want the option to open the Excel file without saving then
' comment out the line below
' Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Grid_Bad_Meters.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()
'Grid_Bad_Meters.AllowPaging = True
'Grid_Bad_Meters.AllowSorting = True
'GridView1.DataSource = dt
'GridView1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim ScriptManager As ScriptManager = ScriptManager.GetCurrent(Me.Page)
ScriptManager.RegisterPostBackControl(Me.btnExportToExcel)
Catch ex As Exception
End Try
End Sub
Protected Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click
Try
Dim sw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(sw)
Dim style As String = "<style>.textmode{mso-number-format:\#;}</style>"
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=SignExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
For i As Integer = 0 To Me.Grid_Bad_Meters.Rows.Count - 1
Dim row As GridViewRow = Grid_Bad_Meters.Rows(i)
row.Attributes.Add("class", "textmode")
Next
'lblRptHeader.RenderControl(hw)
hw.WriteBreak()
'lblReportDateRange.RenderControl(hw)
Grid_Bad_Meters.RenderControl(hw)
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
Catch ex As Exception
End Try
End Sub
You could use one of the two approaches mentioned below. Of course, there are other ways of meeting your requirement like exporting to csv file as mentioned in a comment or using a .Net library meant for Excel exporting like epplus.
OpenXML Approach
If you are looking for a way to export to Excel without using the html approach, then you can use OpenXML approach that is explained very clearly with a working example at this URL: Export to Excel using OpenXML. This will eliminate all the CSS styles that can get associated with exporting using html approach and you seem to be using this html approach according to the code in your original post. However, if you want to use the html approach, then the code below should work and eliminate all CSS styles that can come in the way when viewing the excel file. I have actually tried this posted code on my machine before putting it here.
Html Approach
You can create a new instance of GridView in your export method rather than use an existing instance, and data bind it to same data as the existing gridview on your page before rendering it to excel. Before you data bind it in the export method you need to make sure that no styles are set and specifically the grid line are set to none as in code below.
You can see an actual video of how this works at this URL : Grid Export without any CSS Styles. This was how the code behaved on my laptop when I ran it.
You can use sample code below, but make sure the data source is set to data that includes all records across all pages of original gridview. I have used SqlDataSource1 as data source but you can replace it by an appropriate method in your situation.
Protected Sub btnExport_Click(sender As Object, e As EventArgs)
Dim GridView2 As New GridView()
GridView2.AllowPaging = False
GridView2.AllowSorting = False
GridView2.Style.Clear()
GridView2.CellPadding = 0
GridView2.CellSpacing = 0
GridView2.GridLines = GridLines.None
GridView2.BorderStyle = BorderStyle.None
GridView2.BorderWidth = Unit.Pixel(0)
GridView2.AlternatingRowStyle.BorderStyle = BorderStyle.None
GridView2.DataSource = SqlDataSource1
GridView2.DataBind()
' Clear the response
Response.Clear()
' Set the type and filename
Response.AddHeader("content-disposition", "attachment;filename=griddata.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
' Add the HTML from the GridView to a StringWriter so we can write it out later
Dim sw As New System.IO.StringWriter()
Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
GridView2.RenderControl(hw)
' Write out the data
Response.Write(sw.ToString())
Response.[End]()
End Sub
Public Overrides Property EnableEventValidation() As Boolean
Get
Return False
End Get
'Do nothing
Set
End Set
End Property
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
'Allows for printing
End Sub
I have a GridView that I need to export into Excel (by button event) and I'm using Visual Studio and vb.net.
I never tried this before and I'm kinda clueless, is there a simple way to do this? I don't think I need any complications at the moment, just a simple export of the GridView information.
Also I already got a connection between the GridView and my database. I tried adding a working Excel export from other project but I still miss something .
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub exportExelBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exportExelBtn.Click
Dim errorCheck As Integer = 0
Dim popupscript As String = ""
If approvalGrid.Rows.Count > 0 Then
Try
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "TestPage.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
' Dim sw As New stringwriter()
Dim tw As New IO.StringWriter()
Dim htw As New HtmlTextWriter(tw)
approvalGrid.RenderControl(htw)
Response.Write(tw.ToString())
Response.[End]()
Catch ex As Exception
errorCheck = 1
End Try
Else
errorCheck = 1
End If
If errorCheck = 1 Then
'a pop up error messege feature
popupscript = "<script language='javascript'>" + "alert(" + Chr(34) + "There was an error in exporting to exel, please make sure there is a grid to export!" + Chr(34) + ");</script>"
End If
Page.ClientScript.RegisterStartupScript(Me.GetType(), "PopUpWindow", popupscript, False)
End Sub
The problem is that the file that it creates upon click says it's not Excel format and when I agree to open it I do see the GridView information as I wanted but I also see a lot of extra info in the form of buttons calanders and other stuff from my page, how can I prevent the export of those other stuff?
Please Try Below code
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnExport_Click(sender As Object, e As EventArgs)
If gridview.Rows.Count > 0 Then
Try
gridview.Columns(0).Visible = False
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "TestPage.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gridview.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
Catch ex As Exception
Finally
gridview.Columns(0).Visible = True
End Try
End If
End Sub
I have written above code to export gridview to excel file, it exports successfully but there are some content in gridview in Persian language which is shown unreadable in exported excel file. the code I have written is as below:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If GridView1.Rows.Count > 0 Then
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "IncentiveReport.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
Dim sw As New IO.StringWriter()
Dim htw As New HtmlTextWriter(sw)
GridView1.RenderControl(htw)
Response.Write(sw.ToString())
Response.End()
End If
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
I am new to ASP.net web programming and I am trying to develop a web application that will transfer CSV file data to gridview in asp.net. For example I have below url:
http://sam.sample.com/samp/DATA.CSV
Above url must be transferred in gridview using asp whenever the file has been uploaded,so meaning the date and time of uploading must be displayed also.
I have tried below codes but got an error:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim cls As Class1 = New Class1()
Dim webrequest As System.Net.HttpWebRequest
Dim URL As String = "http://sam.sample.com/samp/DATA.CSV"
Dim csvuri As New Uri(URL)
webrequest = DirectCast(System.Net.HttpWebRequest.Create(csvuri), System.Net.HttpWebRequest)
webrequest.UseDefaultCredentials = True
webrequest.PreAuthenticate = True
webrequest.Credentials = New Net.NetworkCredential("ABC", "A123")
If (webrequest.GetResponse().ContentLength > 0) Then
Dim strReader As New System.IO.StreamReader(webrequest.GetResponse().GetResponseStream())
cls.CreateCSVTable(strReader.ReadLine())
While (InlineAssignHelper(SingleLine, strReader.ReadLine())) IsNot Nothing
cls.AddRowCSVTable(SingleLine)
End While
GridView1.DataSource = cls.CSVTable
GridView1.DataBind()
If strReader IsNot Nothing Then
strReader.Close()
End If
End If
Catch ex As System.Net.WebException
MsgBox(ex.ToString)
End Try
End Sub
Public Sub CreateCSVTable(ByVal TableColumnsList As String)
CSVTable = New DataTable("CSVTable")
Dim myDataColumn As DataColumn
Dim ColumnName As String() = TableColumnsList.Split(",")
For i As Integer = 0 To ColumnName.Length - 2
myDataColumn = New DataColumn()
myDataColumn.DataType = Type.GetType("System.String")
myDataColumn.ColumnName = ColumnName(i)
CSVTable.Columns.Add(myDataColumn)
Next
End Sub
Public Sub AddRowCSVTable(ByVal RowValueList As String)
Dim RowValue As String() = RowValueList.Split(","c)
Dim myDataRow As DataRow
myDataRow = CSVTable.NewRow()
For i As Integer = 0 To RowValue.Length - 2
myDataRow(i) = RowValue(i)
Next
CSVTable.Rows.Add(myDataRow)
End Sub
The error was "Cannot find column 0" which points on:
myDataRow(i) = RowValue(i)
How can I resolve this error. Thanks in advance.
I have created a sample solution here: Sample Solution
Hope this helps you.
I am able to export a gridview to excel, my problem is that I cannot figure out how to remove the formatting from coming over from the girdview. Here is the code I am using to export the gridview:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Clear()
Response.Charset = ""
'Response.ContentType = "application/vnd.ms-excel"
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim stringWrite = New System.IO.StringWriter()
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
GridView1.GridLines = GridLines.None
GridView1.HeaderStyle.Font.Bold = True
GridView1.DataSourceID = SqlDataSource1.ID
GridView1.DataBind()
GridView1.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString)
Response.End()
End Sub
What I suggest that you should iterate datasource , append the content of each row into StringBuilder object and write that string to the response buffer.