Gridview to .xlsx - asp.net

Wondering if someone could give me answer and some tip if it's possibly to export a grindview to a .xlsx (2007 versions of excel).
I have manage to transfer the grindview to .xls (2003 excel) but not to xlsx.
my code is:
Regards
Lime3003
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" + selReportName + " .xls")
Response.Charset = ""
Response.ContentType = "Application / vnd.openxmlformats - officedocument.spreadsheetml.sheet"
'Response.ContentType = "application/vnd.ms-excel"
Using sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
gwResult.GridLines = GridLines.Both
gwResult.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style> .textmode { } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.[End]()
End Using
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub

As Tim Schmelter said I was using EPPlus for export the dataview but I needed to change it to datatable.
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Dim dt As DataTable
dt = dvData.ToTable
'MsgBox(gwResult.HeaderRow.Cells.Count)
Try
Dim pck = New OfficeOpenXml.ExcelPackage()
Dim ws = pck.Workbook.Worksheets.Add(selReportName)
ws.Cells("A2").LoadFromDataTable(dt, True)
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=" + selReportName + ".xlsx")
Response.BinaryWrite(pck.GetAsByteArray())
'log error
Catch ex As Exception
End Try
Response.[End]()
End Sub

Related

When I download the Excel File from the website I am unable to see it's contents

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

PDF download doesnt work, instead opening unreadable in browser

I have an asp.net application which allows user to download PDF files. but instead of downloading it, the browser opens the file with unreadable block characters.
Download Code
Protected Sub btn_dwnd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_dwnd.Click
cn.Open()
cmd.CommandText = "Select * from Syllabus where file_name ='" & txtdwd_file.Text & "'"
cmd.Connection = cn
dr = cmd.ExecuteReader
Do While dr.Read
Response.WriteFile(dr("file_name"))
Loop
cn.Close()
End Sub
I am trying to download my uploaded pdf file in my project's root directory D:\OLMS when I click download unreable characters opens up in browser (square characters). I think it opens up pfd file in browser
Upload Code
Protected Sub btnadd_sylbus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnadd_sylbus.Click
Dim extension As String = System.IO.Path.GetExtension(FileUpload_sylbus.PostedFile.FileName).ToLower()
Dim Type As String = Nothing
If (extension = ".pdf") Then
Dim strFileNamePath As String
Dim strFileNameOnly As String
strFileNamePath = FileUpload_sylbus.PostedFile.FileName
strFileNameOnly = Path.GetFileName(strFileNamePath)
Dim newFileNamePath As String = Path.Combine("D:\OLMS", strFileNameOnly)
Dim br As New BinaryReader(FileUpload_sylbus.PostedFile.InputStream)
FileUpload_sylbus.PostedFile.SaveAs(newFileNamePath)
cmd.CommandText = "INSERT into Syllabus(sylbus_id, sylbus_name, file_name, content) values(#id,#name,#file,#cont)"
cmd.Connection = cn
cmd.Parameters.Add("#id", txtsylbus_id.Text)
cmd.Parameters.Add("#name", txtsylbus_name.Text)
cmd.Parameters.Add("#file", FileUpload_sylbus.FileName)
cmd.Parameters.Add("#cont", br.ReadBytes(FileUpload_sylbus.PostedFile.ContentLength))
cmd.ExecuteNonQuery()
cn.Close()
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "File Upload Success."
txtsylbus_id.Text = Nothing
txtsylbus_name.Text = Nothing
Else
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "Not a Valid file format"
End If
End Sub
Thanx guys it worked :D
Response.ClearHeaders()
Response.ClearContent()
Response.ContentType = "application/octet-stream"
Response.Charset = "UTF-8"
Response.AddHeader("content-disposition", "attachment; filename=" & dr("file_name"))
Response.WriteFile("D:\OLMS\" & dr("file_name"))
Response.End()

Simple export from ASP.NET GridView into Excel VB.NET

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

System.OutOfMemoryException when exporting GridView to Excel

I have a sub that exports a ASP Gridview to excel, it works fine, however, when there are a large amount of rows I get this error:
Exception of type 'System.OutOfMemoryException' was thrown.
Any ideas how to solve this? Here is my export to excel sub:
Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportMonth.Click
Dim title As String
title = "MonthlyReportUK"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", title))
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(Encoding.Unicode.GetPreamble())
Dim strWr As New StringWriter()
Dim HtmlWr As New HtmlTextWriter(strWr)
monthlyReportsIE.AllowPaging = False
monthlyReportsIE.DataBind()
monthlyReportsIE.RenderControl(HtmlWr)
Response.Write(strWr.ToString())
Response.End()
End Sub
You can try rendering the control directly to the output stream by using a StreamWriter and avoid creating a large string in memory. You can also try setting Response.Buffer to False and the server will send the output to the client directly as it is processed.
Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportMonth.Click
Dim title As String
title = "MonthlyReportUK"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", title))
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(Encoding.Unicode.GetPreamble())
Response.Buffer = False
monthlyReportsIE.AllowPaging = False
monthlyReportsIE.DataBind()
Using strWr As new StreamWriter(response.OutputStream)
Using htmlWr As new HtmlTextWriter(strWr)
monthlyReportsIE.RenderControl(htmlWr)
End Using
End Using
Response.End()
End Sub
If this answer is not valid in your case, then you should consider an external library to do the job, because exporting large Excel files as HTML is memory consuming.
Check this sample about how to export the datatable of gridview.

export gridview to excel without the gridview formatting VB

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.

Resources