简体   繁体   中英

export grid view to excel using C#

I have created a page which will accept SharePoint list name as query string and generate an excel file

I am trying to export to excel using the below code

ListName = ListName.Replace(" ", "");
string attachment = "attachment; filename=" + ListName + ".xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel 8.0";
HttpContext.Current.Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(sw);
gridview.DataSource = _dtFramedTable;
gridview.DataBind();

htmlwriter.AddAttribute("xmlns:x", "urn:schemas-microsoft-com:office:excel");
htmlwriter.RenderBeginTag(HtmlTextWriterTag.Html);
htmlwriter.RenderBeginTag(HtmlTextWriterTag.Head);
htmlwriter.RenderBeginTag(HtmlTextWriterTag.Style);
htmlwriter.Write("br {mso-data-placement:same-cell;}");
htmlwriter.RenderEndTag();
htmlwriter.RenderEndTag();
htmlwriter.RenderBeginTag(HtmlTextWriterTag.Body);
gridview.RenderControl(htmlwriter);
htmlwriter.RenderEndTag();
htmlwriter.RenderEndTag();
HttpContext.Current.Response.Write(HttpUtility.HtmlDecode(sw.ToString()));
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.Close();

This exports gridview to excel, but when I open the excel file, it says

file format and extension of don't match. the file could be corrupted or unsafe unless you trust the source, don't open it

How can this be avoided?

HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=\""+Export.xls+"\"; filename*=UTF-8''"+Uri.EscapeDataString(Export.xls)); );
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "example.xls"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM