概述
在做.Net web开发的过程中经常需要将查出的数据导成Excel表返给用户,方便用户对数据的处理和汇总。这里我将导出Excel表格的代码做一个总结,这也是我项目中经常用到的,代码简单易懂,使用方便,分享给大家。
1、查询数据,数据需要是datatable
后端代码实例,先给Excel表头转化为中文描述
1 public OperationResult CreateExportExcel(Model queryModel) 2 { 3 string errorMsg; 4 DataSet ds = GetService.RunPRC_ConfirmCompSKD(queryModel, out errorMsg); 5 if (!string.IsNullOrEmpty(errorMsg)) 6 { 7 return new OperationResult("99", errorMsg); 8 } 9 if (ds.Tables.Count != 2) 10 { 11 return new OperationResult("99", "查询为空"); 12 } 13 DataTable dt = ds.Tables[0]; 14 dt.Columns.Remove(dt.Columns["DeptID"]); 15 dt.Columns.Remove(dt.Columns["SearchKey"]);//删除不需要的列 16 dt.Columns["FYear"].ColumnName = "年份"; 17 dt.Columns["FMonth"].ColumnName = "月份"; 18 dt.Columns["FranchiseeNo"].ColumnName = "编号"; 19 dt.Columns["FranchiseeName"].ColumnName = "名称"; 20 dt.Columns["DeptName"].ColumnName = "维护部门"; 21 dt.Columns["FContractNo"].ColumnName = "合同编号"; 22 dt.Columns["FDate1"].ColumnName = "起租日期"; 23 dt.Columns["FDate2"].ColumnName = "止租日期"; 24 dt.Columns["FNumber"].ColumnName = "收款单编号"; 25 dt.Columns["FAmount"].ColumnName = "收款金额"; 26 dt.Columns["FDate"].ColumnName = "收款日期"; 27 dt.Columns["SkdNo"].ColumnName = "已核销收款单编号"; 28 dt.Columns["SkdAmount"].ColumnName = "已核销收款金额"; 29 dt.Columns["SkdDate"].ColumnName = "已核销收款日期"; 30 return Export(dt, "收款单-"); 31 } 32 /// <summary> 33 /// 生成导出临时文件 34 /// </summary> 35 /// <param name="dt"></param> 36 /// <param name="preName"></param> 37 /// <returns></returns> 38 private OperationResult Export(DataTable dt, string preName) 39 { 40 41 dt.TableName = preName + DateTime.Now.ToString("yyyyMMddHHmmss"); 42 43 string baseDictory = AppDomain.CurrentDomain.BaseDirectory; 44 45 string dirctory = string.Format("{0}Doc", baseDictory); 46 47 if (!Directory.Exists(dirctory)) 48 { 49 Directory.CreateDirectory(dirctory); 50 } 51 52 string path = string.Format("{1}Doc/{0}.xls", dt.TableName, baseDictory); 53 54 string serverPath = path; 55 56 if (File.Exists(serverPath)) 57 { 58 File.Delete(serverPath); 59 } 60 61 ExcelUtil.SaveAsExcel(serverPath, preName, dt); 62 63 bool flag = File.Exists(serverPath); 64 65 if (!flag) 66 { 67 return new OperationResult("01", "生成失败"); 68 } 69 70 var result = new OperationResult("00", "success") 71 { 72 returnURL = string.Format("/Doc/{0}", Path.GetFileName(serverPath)) 73 }; 74 75 return result; 76 }
public class OperationResult { public OperationResult() { } public OperationResult(string errCode, string errMsg) { ErrorCode = errCode; ErrorMsg = errMsg; } /// <summary> /// 返回状态 /// </summary> public bool Flag { get; set; } /// <summary> /// 返回码 /// </summary> public string ErrorCode { get; set; } /// <summary> /// 返回的URL /// </summary> public string returnURL { get; set; } /// <summary> /// 返回消息 /// </summary> public string ErrorMsg { get; set; } public object ObjectData { get; set; } public object rows { get; set; } public int total { get; set; } /// <summary> /// 页脚 /// </summary> public object footer { get; set; } }
前端代码实例:
function outExcel() { var queryUrl = "/Statistics/D_IComeData/CreateD_MonthIncomeExportExcel"; var queryModel = form2Json("searchform"); $.ajax({ type: "POST", url: queryUrl, data: queryModel, dataType: "JSON", success: function (result) { var row = result.rows; if (Util.isValidResult(row)) { if (row.hasOwnProperty("returnURL") && row.returnURL != null) { OpenFrameUrl(row.returnURL); } } } }); } function OpenFrameUrl(url) { var form = document.createElement("form"); form.id = "outExcelResult"; form.action = url; form.method = "get"; document.body.appendChild(form); form.submit(); document.body.removeChild(form); };