Export Gridview with image to Excel - Problem - asp.net

I have a Gridview in my ASP.NET C# Page. It has a couple of columns and also one image column. I can export the entire columns to an Excel file, but the image column is blank. By the way, I use the full path.
Any Idea?

Yes in default.aspx (For local Export)
ImageUrl="http://localhost:4056/CSharp/banner.gif"
instead of ImageUrl="~/banner.gif"
or (For remote Export)
http://your ip address here :port/foldername/filename

Response.Clear(); //this clears the Response of any headers or previous output
Response.Buffer = true; //make sure that the entire output is rendered simultaneously
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView2.GridLines = GridLines.Both;
GridView2.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();

Related

Export Excel from grid not working on Ajax Model PopUp

Hi i am trying to export grid data to excel but it is not working in IE8.I am using a Ajax Modal PopUp dialog box containing 2 buttons 'ok' and 'close'.On Ok click i want to download excel file.it works fine in Mozilla but in IE its not working.I am using below code. please suggest me how to do that?Also when i open file first it show warning before opening file how to handle that?
Response.Clear();
Response.Buffer = true;
string filename = "Checkout";
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".adt");
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
Response.Write("<!--[if gte mso 9]><xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>Sheet1</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]--> ");
Response.Write("</head>");
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = true;
gv.DataSource = dt;
gv.DataBind();
gv.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
You get warning because tehnically speaking this is not export to excel, but you send a html with a wrong headers to trick browser to open this content with excel.
Better use native Excel library and generate real Excel file on the server, for example EPPlus, it's open source and doesn't require excel on server.
Here is the example of ashx handler that generates excel file from DataTable
https://stackoverflow.com/a/9569827/351383

Export sqldatasource to excel not just list or gridview

I'm trying to export my listview, but not just the visible listview, I want to export the entire contents of the sqldatasource. The query returns 20 columns, only a small set (5) are displayed on the listview. Is there a way i can export the entire 20 columns to excel file?
I have this so far:
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=SearchResults.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
this.EnableViewState = false;
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
//I want to chagne this:
this.ResultsListView.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
instead of this line:
this.ResultsListView.RenderControl(htmlTextWriter);
I would like to do something like:
this.sqldatasource.RenderControl(htmlTextWriter);
But obviously SqlDataSource doesn't have a RenderControl method. Is there a clean way of going about this?
You can create a DataTable from the DataView returned by the SqlDataSource and export that to Excel. The resulting DataTable will contain all the columns.
Example:
DataTable dt = ((DataView) this.sqldatasource.Select(DataSourceSelectArguments.Empty)).ToTable();
Now take this DataTable and export that. Google export DataTable to Excel.
If you are fine with using third-party libraries, look into EPPLUS. You can export a DataTable to Excel in, literally, 2 lines of code. The rest would be the code to set the headers and flush the Response.
Here's an example: http://epplus.codeplex.com/wikipage?title=WebapplicationExample
I prefer to use CSV rather than excel for plain data, but the new version of Excel does have the advantage of compression.
You can use the OpenXMLSDK to directly export to XLSX or the FileHelpers library to export to CSV.

ASP.Net page export to pdf

I got stuck with my ASP.Net export to PDF. Below are my codes. Please help.
Response.Clear();
Response.Buffer = true;
Response.Charset = Encoding.UTF8.HeaderName;
Response.ContentEncoding = Encoding.UTF8;
Response.Write(string.Format("<meta http-equiv=Content-Type content=text/html;charset={0}>", Encoding.UTF8.HeaderName));
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-disposition", "attachment; filename=pdffilename.pdf");
StringBuilder sb = new StringBuilder();
sb.Append("MIME-Version: 1.0\r\n");
sb.Append("X-Document-Type: Worksheet\r\n");
sb.Append("Content-Type: multipart/related; boundary=\"----=mtrSystem\"\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-Type: text/html; charset=\"utf-8\"\r\n");
sb.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");
sb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:pdf\">\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-ID: baiduimg\r\n");
sb.Append("Content-Transfer-Encoding: base64\r\n");
sb.Append("Content-Type: image/png\r\n\r\n");
Can i use this way to export my ASP.Net page to PDF?
Html-to-pdf.net allows for converting html to pdf. TO get the html from an asp.net page, use the following code:
StringWriter sw = new StringWriter();
Server.Execute("PageToConvert.aspx", sw);
string htmlCodeToConvert = sw.GetStringBuilder().ToString();
Then pass the html to the pdf generator:
public byte[] GetPdfBytesFromHtmlString (string htmlString)
You can then save the bytes to the response to send to client, or save on the server as a local file.
EDIT:
Something to keep in mind, html-to-pdf does cost money, but for my last project it was a justified expense. You can use the trial version to figure out what you needd.
I'm not entirely sure what you're trying to do, but generally I can highly recommend PDFSharp for creating PDF documents in code...

Export a data set to Excel and raise a file download dialog from an asp.net web method

I am using the following code to export a data set to an Excel sheet.
[WebMethod]
public static void ExporttoExcel()
{
DataSet ds;
productfactory pf=new productfactory();
ds = pf.getproducts();
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";
response.Write(sw.ToString());
// response.End();
}
}
}
The problem is that it's not raising file download and hence no export is taking place. The same code works fine in a normal method. But with the web method it's not working.
I suggest to make an HttpHandler ending in ashx, and place inside him your code that create the excel file.
then call it from your javascript code like that.
document.location.href = "ExporttoExcel.ashx";
The problem is that WebMethods are not designed to allow you to interact with the Response object (evident in that it wasn't available and you had to use HttpContext.Current.Response to get to it). WebMethods are designed to be blackbox to the user. They will perform and action and/or return a value.
Perhaps you can give us a better idea of what you are trying to accomplish and we can suggest an alternate solution.
u can use to create a dynamic iframe with URL set to the Web Handler to generate the Excel this will raise the file download with out posting the current page.

Export Repeater to excel

I am trying to export my repeater to excel and here is my code...
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=file.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
rpt.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
When I am trying to open file getting this error
The file you are trying to open, 'file.xls', is in a different format than specified
by the file extension. Verify that the file is not Corrupted and is from a trusted
source before opening the file. Do you want to open the file now?
Yes No Help option are available
What's wrong in my code or What I have to do resolve this issue.
Thanks
You are setting the content type to application/vnd.ms-excel but you are sending HTML contents in the response stream when you call the RenderContents method. You might need a library to generate Excel files.
Try wrapping your content into this:
StringBuilder sb = new StringBuilder("");
sb.Append("<HTML xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><HEAD>");
sb.Append("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
sb.Append("<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>");
sb.Append(title);
sb.Append("</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </HEAD><BODY>");
sb.Append(content);
sb.Append("</BODY></HTML>");

Resources