/// <summary> /// 将一组对象导出成EXCEL /// </summary> /// <typeparam name="T">要导出对象的类型</typeparam> /// <param name="objList">一组对象</param> /// <param name="FileName">导出后的文件名</param> /// <param name="columnInfo">列名信息</param> public static void ExportExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo) { if (columnInfo.Count == 0) { return; } if (objList.Count == 0) { return; } //生成EXCEL的HTML StringBuilder excelStr = new StringBuilder(); Type myType = objList[0].GetType(); //根据反射从传递进来的属性名信息得到要显示的属性 List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>(); excelStr.Append("<?xml version="1.0" encoding="UTF-8"?> "); excelStr.Append("<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" "); excelStr.Append("xmlns:x="urn:schemas-microsoft-com:office:excel" "); excelStr.Append("xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" "); excelStr.Append("xmlns:html="http://www.w3.org/TR/REC-html40"> "); excelStr.Append("<Worksheet ss:Name="Table1"> "); excelStr.Append("<Table>"); excelStr.Append("<Column ss:Index="1" ss:AutoFitWidth="0" ss:Width="110"/> "); excelStr.AppendLine("<Row>"); foreach (string cName in columnInfo.Keys) { System.Reflection.PropertyInfo p = myType.GetProperty(cName); if (p != null) { myPro.Add(p); excelStr.AppendLine("<Cell><Data ss:Type="String">" + columnInfo[cName] + "</Data></Cell>"); } } excelStr.AppendLine("</Row>"); //如果没有找到可用的属性则结束 if (myPro.Count == 0) { return; } foreach (T obj in objList) { excelStr.AppendLine("<Row>"); foreach (System.Reflection.PropertyInfo p in myPro) { excelStr.AppendLine("<Cell><Data ss:Type="String">" + p.GetValue(obj, null) + "</Data></Cell>"); } excelStr.AppendLine("</Row>"); } excelStr.Append("</Table> "); excelStr.Append("</Worksheet> "); excelStr.Append("</Workbook> "); HttpResponse Response = HttpContext.Current.Response; Response.Clear(); Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + System.DateTime.Now.ToString("_yyMMdd_hhmm") + ".xls"); Response.Charset = "gb2312"; Response.ContentType = "application/ms-excel"; Response.Write(excelStr.ToString()); Response.End(); }
使用调用
List<ContractView> contract = GlobalContainer.Resolve<IContractRepository>().GetSortedContractView("ID", true); Dictionary<string, string> colum = new Dictionary<string, string>(); colum.Add("ID", "ID"); colum.Add("ContractNo", "合同编号"); colum.Add("ContractName", "合同名称"); colum.Add("SOW", "SOW"); colum.Add("ParentContractNo", "父合同"); colum.Add("CustomName", "客户名称"); colum.Add("CustomDirectorName", "客户负责人"); colum.Add("WorkMode", "工作模式"); colum.Add("Attachment", "附件"); colum.Add("UnitPrice", "单价"); colum.Add("StartTime", "开始时间"); colum.Add("EndTime", "结束时间"); colum.Add("AccountPeriod", "付款周期"); colum.Add("PaymentMode", "付款方式"); colum.Add("PaymentTerms", "付款期限"); colum.Add("Status", "状态"); colum.Add("CreateTime", "创建时间"); Utility.ExportExcel(contract, "Contract", colum);