MVC export Excel, provide download Excel

Source: Internet
Author: User

Class 1:

Using System.Collections.Generic;
Using System.Data;
Using SYSTEM.WEB.MVC;
Using System.IO;
Using System.Web.UI.WebControls;
Using System.Web;
Using System.Web.UI;
Using System.Drawing;

Namespace Base.actionresult
{
public class ExcelResult:System.Web.Mvc.ActionResult
{
Private DataTable _datacontext;
private string _filename;
Private string[] _headers = null;
Private TableStyle _tablestyle;
Private TableItemStyle _headerstyle;
Private TableItemStyle _itemstyle;

public string FileName
{
get {return _filename;}
}

Public Excelresult (DataTable dataContext, String fileName)
: This (dataContext, fileName, NULL, NULL, NULL, NULL)
{
}

Public Excelresult (DataTable dataContext, String fileName, string[] headers)
: This (DataContext, fileName, headers, NULL, NULL, NULL)
{
}

        public Excelresult (DataTable dataContext, String fileName, string[] Headers, TableStyle TableStyle, TableItemStyle HeaderStyle, TableItemStyle itemstyle)
         {
            _datacontext = DataContext;
            _filename = fileName;
            _headers = headers;
            _tablestyle = TableStyle;
            _headerstyle = HeaderStyle;
            _itemstyle = ItemStyle;

           //provide defaults
             if (_tablestyle = = null)
             {
                 _tablestyle = new TableStyle ();
                _ Tablestyle.borderstyle = Borderstyle.solid;
                _ Tablestyle.bordercolor = Color.Black;
                _ Tablestyle.borderwidth = Unit.parse ("2px");
           }

            if (_headerstyle = = null)
             {
                 _headerstyle = new TableItemStyle ();
                _ Headerstyle.backcolor = Color.lightgray;
           }
       }

public override void Executeresult (ControllerContext context)
{
Create HtmlTextWriter
StringWriter SW = new StringWriter ();
HtmlTextWriter TW = new HtmlTextWriter (SW);

Build HTML Table from Items
if (_tablestyle! = null)
_tablestyle.addattributestorender (TW);

tw. RenderBeginTag (htmltextwritertag.table);

Generate Headers from table
if (_headers = = null)
{
list<string> lst = new list<string> ();
for (int i = 0; i < _datacontext.columns.count; i++)
{
Lst. ADD (_datacontext.columns[i]. ColumnName);
}
_headers = lst. ToArray ();
}

Create Header Row
tw. RenderBeginTag (Htmltextwritertag.thead);

foreach (string header in _headers)
{
if (_headerstyle! = null)
_headerstyle.addattributestorender (TW);

tw. RenderBeginTag (htmltextwritertag.th);
tw. Write (header);
tw. RenderEndTag ();
}

tw. RenderEndTag ();

Create Data Rows
tw. RenderBeginTag (Htmltextwritertag.tbody);

foreach (DataRow Dr in _datacontext.rows)
{
tw. RenderBeginTag (htmltextwritertag.tr);

foreach (string header in _headers)
{
String strvalue = Dr[header]. ToString ();
strvalue = Replacespecialcharacters (strvalue);

if (_itemstyle! = null)
_itemstyle.addattributestorender (TW);

tw. RenderBeginTag (HTMLTEXTWRITERTAG.TD);
tw. Write (Httputility.htmlencode (strvalue));
tw. RenderEndTag ();
}

tw. RenderEndTag ();
}

            tw. RenderEndTag (); Tbody
            tw. RenderEndTag (); Table
            WriteFile (_filename, "application/ Ms-excel ", SW. ToString ());
       }

private static string Replacespecialcharacters (string value)
{
Value = value. Replace ("'", "'");
Value = value. Replace ("", "\" ");
Value = value. Replace ("", "\" ");
Value = value. Replace ("–", "-");
Value = value. Replace ("...", "...");
return value;
}

private static void WriteFile (String fileName, String contentType, string content)
{
HttpContext context = HttpContext.Current;
Context. Response.Clear ();
Context. Response.AddHeader ("Content-disposition", "attachment;filename=" + filename);
Context. Response.Charset = "";
Context. Response.Cache.SetCacheability (Httpcacheability.nocache);
Context. Response.ContentType = ContentType;
Context. Response.Write (content);
Context. Response.End ();
}
}

public static Class Excelcontrollerextensions
{
public static System.Web.Mvc.ActionResult Excel (the This controller controller,
DataTable DataContext, String fileName)
{
return new Excelresult (DataContext, fileName, NULL, NULL, NULL, NULL);
}

        public static System.Web.Mvc.ActionResult Excel (the This Controller Controller,
       DataTable dataContext, String fileName, string[] headers)
        {
             return new Excelresult (DataContext, fileName, headers, NULL, NULL, NULL);
       }

public static System.Web.Mvc.ActionResult Excel (the This controller controller,
DataTable DataContext, String fileName, string[] headers,
TableStyle TableStyle, TableItemStyle HeaderStyle, TableItemStyle ItemStyle)
{
return new Excelresult (DataContext, FileName, headers, TableStyle, HeaderStyle, ItemStyle);
}
}
}

Public ActionResult GenerateExcel1 ()
//{
return this. Excel (DT, "Data.xls");
//}

Controller method:

Public ActionResult Exportexcel (string param1, String startTime, String endTime)
{
DateTime start = Convert.todatetime (StartTime);
DateTime end = Convert.todatetime (EndTime);

DataTable dt = _srv. Exportexcel (Param1,start, end);
return this. Excel (DT, "Statistics 111.xls");
}

Js:

Click the "Export" button to execute the following JS:


var param = "Starttime=" + startTime + "&endtime=" + endTime
+ "&param1=" + param1;

window.open ("/query/exportexcel" + param);

MVC export Excel, provide download Excel

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.