直接上代碼:public static byte[] GetExecl(DataTable dt, List list) { var sbHtml = new StringBuilder(); sbHtml.Append(""); ...
直接上代碼:
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
代碼寫的有點亂,請忽略