当前位置: 代码迷 >> VC/MFC >> mvc简略execl导出
  详细解决方案

mvc简略execl导出

热度:114   发布时间:2016-05-02 03:19:37.0
mvc简单execl导出

直接上代码:

public static byte[] GetExecl(DataTable dt, List<string> list)        {            var sbHtml = new StringBuilder();            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");            sbHtml.Append("<tr>");            foreach (var item in list)            {                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);            }            sbHtml.Append("</tr>");            for (int i = 0; i < dt.Rows.Count; i++)            {                sbHtml.Append("<tr>");                for (int j = 0; j < list.Count; j++)                {                    sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", dt.Rows[i][j].ToString());                }                sbHtml.Append("</tr>");            }            sbHtml.Append("</table>");            byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString());            return fileContents;        }
View Code

这样可以写成公共方法方便多次调用

public FileResult ExportExcel(int page,int PageSize,string CusName="")        {            var orderby = "order by Createdate desc";            var wherestr = "";            //要导出的字段            var tablefield = "ID,CusName,CusShort,Salesman,Industry,CusType,CusAdrss,Region,CusContact,"                + "CusIphone,CusMobile,FinName,FinIphone,FinMail,FinFax,Qqnumber,BankAccount,"                + "BankDeposit,TariffItem,TpayerDate,Contracttime,Remark,VerifierYes,"                + "Verifier,Verifierdate,Creater,Createdate,Updater,Updatedate";            if (CusName != "")            {                wherestr = "and CusName like '%" + CusName + "%'";            }            //得到要导出的数据            DataSet ds = DAL.SQLBasic.GetDateSetfengye(PageSize, page, tablename, wherestr, orderby, tablefield);            //设置execl第一行标题            List<string> list = new List<string> { "客户编号","客户名称","客户简称",                "所属业务员","行业","客户类型","客户地址","区域","指定联系人",                "联系人电话","联系人手机","财务员","财务员电话","财务员邮箱","财务员传真","财务员QQ","银行账号",                "开户行","税号","成为纳税人时间","合同有效期","备注","是否审核",                "审核人","审核时间","创建人","创建时间","修改人","修改时间"};            byte[] fileContents = Utilitiy.ExcelHelper.GetExecl(ds.Tables[0], list);                        return File(fileContents, "application/ms-excel", "客户信息.xls");        }
View Code

代码写的有点乱,请忽略