We want to create a CSV file from data .It is showing HTML tags .Same working fine for xlx file.
Below is code.
Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
response.Clear()
response.ClearHeaders()
response.Write("<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""/>")
'Chose what type of file needed ie.e CSV /XLS
If _exportType = ExportTypeEnum.CSV Then
response.ContentType = "application/vnd.xls"
Else
response.ContentType = "application/vnd.xls"
End If
response.AddHeader("Content-Disposition", "attachment;filename=" & FileNameToExport)
Dim sw As System.IO.StringWriter = New StringWriter()
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
Dim dg As DataGrid = New DataGrid()
Dim dv1 As DataView = data
dg.DataSource = dv1
dg.BorderStyle = BorderStyle.None
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.End()
Please suggest WHY it is not working for CSV file , although it is fine for xls file.
Many thanks in advance
You're explicitly writing the output in HTML format. Notice this line:
response.Write("<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""/>")
And notice the object you're using to write output:
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
This is all emitting HTML to the output. It "works fine" for an Excel file because Excel understands HTML structures when rendering a file. CSV, however, is a much "flatter" format and only knows plain text (delimited by a comma). You'll also see the HTML tags if, for example, you use this code to write to a .txt file.
If you want a CSV file without HTML, you shouldn't write HTML content to it.
Related
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'm using ASP.net with VB codebehind.
I need to be able to convert an excel file created in code into a byte array in order to send it to the client. Without saving the file to the server.
this is how i created the excel document
Dim APP As Excel.Application = New Excel.Application
Dim missing As Object = System.Reflection.Missing.Value
Dim Workbook As Excel.Workbook = (APP.Workbooks.Add(missing))
Dim worksheet As Excel.Worksheet = Workbook.ActiveSheet
'..Fill cells in worksheet..
This is how i transmit it:
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.Cookies.Clear()
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.CacheControl = "private"
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8
Response.AppendHeader("Content-Length", filebytes.Length.ToString())
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Expires", 60)
Response.AppendHeader("Conetnt-Disposition", "attachement; filename='MostIssuesByModelReport.xlsx'; size=" & filebytes.Length.ToString() & "; creation-date=" & Date.Now.ToString("R") & "; modification-date=" & Date.Now.ToString("R") & "; read-date=" & Date.Now.ToString("R"))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'write to client
Response.BinaryWrite(filebytes)
Response.End()
I just need to get the content of Workbook into filebytes
EDIT:
After looking around a bit more I can now make it download a file, however this file does not use the filename specified in the above code, it uses the name of the asp server page that the user is on, it also has a .aspx extension..however if I force it to open in excel it is correct. Besides popping up saying the source may be corrupted. Why is this happening and how can I fix it?
In an ASP.NET site, I am rendering a GridView control to export it's details in a excel file
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Type", "application/vnd.ms-excel")
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
gridviewObject.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()
Now, it's getting rendered,but the gridview uses few images to beautify the data.
While exporting the data I don't want to show images in excel.
So I want to find the tag and want to replace it by blank string.
Can anybody tell me how I can do that?
I like to compress the xmldata before the data is provided to the client as an excel file. I am trying to compress and deliver it as a .zip file. its not working Here's my code below. Please help
I tried compressing it, converting it to bytes etc etc. The issue with below code is, the XSL transformation is not happening properly and the output excel file is raw xml with some .net exception at the end. (that's what I see on the .xls file that's downloaded at the end)
Before I started working on compression my below code was working fine that gives properly formatted excel file from the xml input. the excel file is so nice you can't even tell it was from XML.
pLEASE HELP with compression
Dim attachment As String = "attachment; filename=DataDownload.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
'Response.ContentType = "text/csv"
Response.Charset = ""
Dim ds As New DataSet()
Dim objXMLReader As XmlReader
objXMLReader = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteXmlReader(ConnectionString, CommandType.StoredProcedure, "SPName")
ds.ReadXml(objXMLReader)
Dim xdd As New XmlDataDocument(ds)
Dim xt As New XslCompiledTransform()
'xt.Transform(xdd, Nothing, Response.OutputStream)
Dim bytearr() As Byte
bytearr = System.Text.Encoding.Default.GetBytes(xdd.OuterXml)
Dim objMemStream As New MemoryStream()
objMemStream.Write(bytearr, 0, bytearr.Length)
objMemStream.WriteTo(Response.OutputStream)
xt.Transform(xdd, Nothing, Response.OutputStream)
Response.End()
Why you don't use XLSX-Format instead of XLS? It is already XML-Data compressed in a ZIP file. You can rename a XLSX file to ZIP to verify this.
Updated: By the way, ContentType in the case should be "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" instead of "application/vnd.ms-excel".
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