MVC导出Excel,提供下载Excel

技术分享

 

类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(this Controller controller,
         DataTable dataContext, string fileName)
        {
            return new ExcelResult(dataContext, fileName, null, null, null, null);
        }

        public static System.Web.Mvc.ActionResult Excel(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(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");
//}

 

 

 

 

 

 

控制器方法:

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, "统计111.xls");
     }

js:

点击 “导出”按钮,执行下面的js:


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

window.open("/Query/ExportExcel?" + param);

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。