Common/ExportExcel.cs

(开头部分) 8KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;

namespace Common
{
    public class ExportExcel : Controller
    {
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="FileName">文件名称不带后缀</param>
        /// <param name="lstTitle">表头</param>
        /// <param name="dst">数据集合</param>
        /// <returns></returns>
        public FileResult OutPutExcel(string FileName, List<string> lstTitle, List<string> lstFileName, DataTable dt = null)
        {
            var sbHtml = new StringBuilder();
            //防止中文乱码
            sbHtml.Append("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            //var lstTitle = new List<string> { "编号", "姓名", "年龄", "创建时间" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sbHtml.Append("<tr>");
                    foreach (var item in lstFileName)
                    {
                        sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", dt.Rows[i][item].ToString());
                    }
                    sbHtml.Append("</tr>");
                }
            }
            sbHtml.Append("</table>");


            //第一种:使用FileContentResult
            byte[] fileContents = Encoding.GetEncoding("utf-8").GetBytes(sbHtml.ToString()); //Default,utf8有时中文乱码
            //string Name = FileName + ".xls";
            //return File(fileContents, "application/ms-excel", Name);

            ////第二种:使用FileStreamResult
            var fileStream = new MemoryStream(fileContents);
            string Name = FileName + ".xls";
            return File(fileStream, "application/ms-excel",Name);

            ////第三种:使用FilePathResult
后面还有 140 行代码,购买后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。