ASP. NET Export Excel file

Source: Internet
Author: User

Before doing the Winfrom program of export Excel file function, feel very simple. Now try to do the ability to export excel in ASP, before using the Microsoft.Office.Interop.Excel object to achieve data export Excel, it is completely disgusting to the ASP. First, the Save dialog box cannot be popped, and then again in code execution to Microsoft.Office.Interop.Excel.Application myexcel = new Microsoft.Office.Interop.Excel.Application (); This sentence, inexplicably not move, the problem in the debugging time did not appear, after the release only came out, and then found a way to solve, is in the configuration file < system.web> add <identity impersonate= "true" username= "Administrator" password= "0"/>, where the user name and password is the local user name and password. After this problem has been solved, and then encountered the painful SaveAs save exception, error prompt is: Exception from Hresult:0x800a03ec. Searching the internet for information has failed to solve the problem. I had to try other options for exporting Excel.

The following scenario is what I want most, a simple and concise introduction:

The first is to build a Web page, which is a button for exporting Excel, the code is as follows:

"http://www.w3.org/1999/xhtml">"Server"> <title></title> <script type="Text/javascript">//Excel DownLoadfunction Excelexport () {//var hidtext = document.getElementById ("Hidparam");//Hidtext.value = "some params";document.getElementById ("Exceloutput"). Click (); } </script> "Form1"runat="Server"> <input type="Button"Value="Excel Download"style="width:100px;"onclick="Excelexport ()"Id="excelbut"/> <%--<input id="Hidparam"Type="text"runat="Server"style="Display:none;"/>--%><asp:button runat="Server"Id="Exceloutput"style="Display:none"text="Excel Output"Width="0px"onclick="Btnexcel_click"Usesubmitbehavior="false"/> <asp:gridview id="Gvexcel"runat="Server"height="95px"visible="False"></asp:GridView> </form></body>

The commented out section can be used to pass the data you want to the backend code.

The background code is as follows:

 Public Partial classWebForm2:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) {                   }               protected voidBtnexcel_click (Objectsender, EventArgs e) {            stringStrexcelname ="Myexcel.xls"; Strexcelname= Strexcelname.replace (@"/",""); DataTable DT=NewDataTable (); DataColumn DC=NULL; DC= dt. Columns.Add ("numbering", Type.GetType ("System.Int32")); DC= dt. Columns.Add ("Product", Type.GetType ("System.String")); DC= dt. Columns.Add ("version", Type.GetType ("System.String")); DC= dt. Columns.Add ("Description", Type.GetType ("System.String")); DataRow Dr=dt.            NewRow (); dr["numbering"] =1; dr["Product"] ="This place is the value of the cell."; dr["version"] ="2.0"; dr["Description"] ="This place is the value of the cell."; Dt.            Rows.Add (DR); Dr=dt.            NewRow (); dr["numbering"] =2; dr["Product"] ="This place is a 333-cell value."; dr["version"] ="3.0"; dr["Description"] ="This place is the 33 value of the cell."; Dt.                        Rows.Add (DR); Gvexcel.visible=true; Gvexcel.datasource=NULL; Gvexcel.datasource=DT;            Gvexcel.databind (); exportToExcel ( This.         Page, Gvexcel, strexcelname); }         Public voidexportToExcel (System.Web.UI.Page Page, GridView Excel,stringfileName) {              Try               {                 foreach(GridViewRow rowinchExcel. Rows) { for(inti =0; I < row. Cells.count; i++) {Excel. Headerrow.cells[i]. BackColor=System.Drawing.Color.Yellow; }} Excel. Font.Size=Ten; Excel. Alternatingrowstyle.backcolor=System.Drawing.Color.LightCyan; Excel. Rowstyle.height= -; //page. Response.appendheader ("Content-disposition", "attachment;filename=" + httputility.urlencode (filename, SYSTEM.TEXT.ENCODING.UTF8)); //If there is a garbled Chinese, use this sentencePage. Response.appendheader ("content-disposition","attachment;filename="+fileName); Page. Response.Charset="Utf-8"; Page. Response.ContentType="Application/vnd.ms-excel"; Page. Response.Write ("<meta http-equiv=content-type content=text/html;charset=utf-8>"); Excel. Page.enableviewstate=false; Excel. Visible=true; Excel.                 Headerstyle.reset (); Excel.                 Alternatingrowstyle.reset (); System.IO.StringWriter Ostringwriter=NewSystem.IO.StringWriter (); System.Web.UI.HtmlTextWriter Ohtmltextwriter=NewSystem.Web.UI.HtmlTextWriter (Ostringwriter); Excel.                 RenderControl (Ohtmltextwriter); Page.                 Response.Write (Ostringwriter.tostring ()); Page.                 Response.End (); Excel. DataSource=NULL; Excel. Visible=false; }                Catch(Exception e) {} }}

In order to highlight the focus of the presentation, there is no introduction to data acquisition. There's a problem here, when the program executes

Excel. RenderControl (Ohtmltextwriter); In this sentence, I reported a mistake: the control must be placed in the form tag with runat=server, this only needs to rewrite the method Verifyrenderinginserverform.
 Public Override void Verifyrenderinginserverform (Control control)        {            //  This method must be required, otherwise excel in the code below. RenderControl (Ohtmltextwriter); Error: The control must be placed inside the form tag with Runat=server        }

Before I did this export function in VS2010 did not encounter this problem, but in vs2013 encountered.

Well, that's the way it's done, and the good thing about it is that there are no messy exceptions, and a popup box is used to select the saved path.

ASP. NET Export Excel file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.