I want to export to excel, but I want to choose the excel file that has the customized coloring and modification instead of the default excel page. How can I achieve this on asp.net with vb.
Take a look also on EasyXLS library. For exporting to excel, you can start with this code sample:
http://www.easyxls.com/manual/FAQ/export-to-excel-in-dot-net.html
Try using specific libraries for export to excel in asp.net. For example exist Syncfusion XlsIo, Telerik or spreadsheetgear (This is specializing in excel). In my case I'm using Syncfusion XlsIo and with this customize all the reports in excel, also can use graphics and conditional formats
Public Sub ExportToExcel (dt As DataTable)
If dt.Rows.Count > 0 Then
Dim filename As String = "DownloadMobileNoExcel.xls"
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", (Convert.ToString("attachment; filename=") & filename) + "")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.End()
End If
End Sub
Related
I want to print a gridview and a labels in header and label in footer ( after the gridview populated )
to use CrystalReports or window.print
or anything else that make my goal achived ( specialy something that easy to use )
Easiest way is to export the datagrid, download and print from Excel.
Dim dg As System.Web.UI.WebControls.DataGrid 'For example if your grid was called dg
Dim reportTitle As String = "Add A Title - Since DataGrid Doesn't Have One"
'export to excel
context.Response.Buffer = True
context.Response.ClearContent()
context.Response.ClearHeaders()
context.Response.ContentType = "application/vnd.ms-excel"
EnableViewState = True
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
dg.RenderControl(hw) '<-- built-in Method of all System.Web.UI.Control objects
Context.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" & reportTitle & "</font></center></b>")
Context.Response.Write(tw.ToString())
Context.Response.Flush()
Context.Response.Close()
Context.Response.End()
For more info, you can check the Microsoft docs https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.rendercontrol
Basic principle is that I am trying to take a GridView and turn it into a PDF document. The GridView includes controls like checkboxes and some css classes with some colouring.
I have tried putting this together, but I think I am misunderstanding how something works and now hit a dead end. At present it all compiles and runs, but when you try and open the returned PDF it says it fails to load. The returned file is 1KB in size, so I am guessing that it isn't actually a valid PDF.
I am using iText7 and htmlPDF, with my code looking like this.
Protected Sub ExportToPDF(sender As Object, e As ImageClickEventArgs)
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
gvCSC.DataBind()
gvCSC.RenderControl(hw)
Dim pdfWriter As New PdfWriter(Response.OutputStream)
Dim pdfDoc As New PdfDocument(pdfWriter)
Dim sr As New StringReader(sw.ToString)
pdfDoc.SetDefaultPageSize(New PageSize(PageSize.A4.Rotate))
Dim doc As Document = HtmlConverter.ConvertToDocument(sr.ToString, pdfDoc, New ConverterProperties)
Response.End()
pdfDoc.Close()
End Using
End Using
End Sub
I am hoping that I am just being stupid as I've not used iText7 before and it just needs someone to point out the obvious for me. Any help in solving this will be appreciated.
Please help
How to export Excel from a SQL Server table using Asp.net & Vb.net supporting Arabic language?
I have used this code:
Dim cmdText As String = "SELECT * FROM ReportView"
Dim command As New SqlCommand(cmdText, Conn)
Conn.Open()
Dim da As New SqlDataAdapter(command)
Dim dt As New DataTable()
da.Fill(dt)
Conn.Close()
Dim GridView1 As New GridView()
GridView1.DataSource = dt
GridView1.DataBind()
Response.Clear()
Response.Buffer = True
Response.Charset = "UTF-8"
Response.ContentType = "application/vnd.ms-excel;charset=UTF-8"
Response.AddHeader("content-disposition", "attachment;filename=Report.xls")
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
But the problem occurs after export Excel file where the words appear as incomprehensible
Ù…Øمد بن راشد آل مكتوم الثانوية للبنين (المزرعة الشرقية)
You're using the wrong MIME content type ("application/vnd.ms-excel;charset=UTF-8").
You cannot generate an actual Excel (*.xls or *.xlsx) file from ASP.NET as they are both complicated file formats (XLS is binary, XLSX is a zip-compressed series of XML documents).
What your code currently does it render a HTML <table> (by abusing the GridView control) and assuming Excel will see it's a HTML table and read it accordingly.
Instead, please either generate a CSV file or output an actual HTML file with the necessary xmlns:o=\"urn:schemas-microsoft-com:office:office\\ xmlns:x="urn:schemas-microsoft-com:office:excel" attributes and elements added.
Because you're abusing Excel's file reader it cannot properly interpret your text content, note the charset attribute of your Content-Type header is ignored by Excel. I believe (though cannot prove) that Excel reads files as Latin1 (or some other 1-byte Western-language encoding) and does not default to UTF-8, even in HTML files unless there's a <meta /> element that specifies the encoding used, but you're only rendering a HTML fragment, a <table> element, without any metadata, which is another reason why it isn't reading it correctly.
I have a webpage with an export button. Is it possible to export a sql table to excel when this button is pressed? I can do it with a gridview but would just like a simple button with code behind to do the work. Can someone point me in the direction I need?
Here is a utility function you can use:
Public Shared Sub ExportToSpreadsheet(table As DataTable, filename As String)
' Get a hold of the HTTP context and clear it, because we are going to push the CSV data through the context
Dim context = HttpContext.Current
context.Response.Clear()
' Loop through each column in your data table
For Each column As DataColumn In table.Columns
' Write column names
context.Response.Write(column.ColumnName + ";")
Next
context.Response.Write(Environment.NewLine)
' Loop through each row in the data table
For Each row As DataRow In table.Rows
' Loop through each column in row
For i As Integer = 0 To table.Columns.Count - 1
' Write each column value
context.Response.Write(row(i).ToString().Replace(";", [String].Empty) & ";")
Next
' Write a new line between rows of data
context.Response.Write(Environment.NewLine)
Next
' Set the content type and headers
context.Response.ContentType = "text/csv"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename & ".csv")
context.Response.[End]()
End Sub
Then you can call it like this:
ExportToSpreadsheet(YourDataTable, "YourFileName")
Note: Since it is a Shared function, then you can put it in a utility class and do not need to instantiate (New) the class to use the function.
If you want it in excel you can use the following code. Select the data and put it in a Gridview and do the following.
Dim GridView1 As New GridView
SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
GridView1.RenderControl(oHtmlTextWriter)
Response.Write(oStringWriter.ToString())
Response.End()
You can also format the Gridview to make it look good on the Excel Sheet.
I am developing an application where i want i am displaying a dataset in the datagrid view for the user.Now the user wants to download the data in the datagridview in an excel format.How can i do it ?
1) should i write the dataset in the excel and save it the server before the user download the file ?
2) Can i use a hyper link and set the path of the file that is saved in the server to the hyper link hRef property , so that the user can click and download the file ?
I am using C# ASP.net 2.0
Please help !
no need to save the file to the sever use the following code, will create the file on the fly:
Public Shared Sub DataTableToExcel(ByVal dt As DataTable, ByVal FileName As String
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Write(Environment.NewLine)
For Each row As DataRow In dt.Rows
For i As Integer = 0 To dt.Columns.Count - 1
HttpContext.Current.Response.Write(row(i).ToString().Replace(";", String.Empty) + ";")
Next
HttpContext.Current.Response.Write(Environment.NewLine)
Next
HttpContext.Current.Response.ContentType = "application/ms-excel"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls")
HttpContext.Current.Response.[End]()
End Sub
you can use this simple code to accomplish
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=SummaryReport" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
grd.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
SpreadsheetGear for .NET will do it.
You can see ASP.NET (C# and VB) samples here and download a free trial here.
Disclaimer: I own SpreadsheetGear LLC