此方法有一個弊端, 就是必須將Entity的屬性對應哪個要輸出的列名(例如:漢字)在調用此方法前事先對應好, 比較煩...
Code
/**//// <summary>
/// 將一組對象匯出成EXCEL
/// </summary>
/// <typeparam name="T">要匯出對象的類型</typeparam>
/// <param name="objList">一組對象</param>
/// <param name="FileName">匯出後的檔案名稱</param>
/// <param name="columnInfo">列名資訊</param>
public void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo)
{
if (columnInfo.Count == 0) { return; }
if (objList.Count == 0) { return; }
//產生EXCEL的HTML
string excelStr = "";
Type myType = objList[0].GetType();
//根據反射從傳遞進來的屬性名稱資訊得到要顯示的屬性
List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>();
foreach (string cName in columnInfo.Keys)
{
System.Reflection.PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
excelStr += columnInfo[cName] + "\t";
}
}
//如果沒有找到可用的屬性則結束
if (myPro.Count == 0) { return; }
excelStr += "\n";
foreach (T obj in objList)
{
foreach (System.Reflection.PropertyInfo p in myPro)
{
excelStr += p.GetValue(obj, null) + "\t";
}
excelStr += "\n";
}
//輸出EXCEL
HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
rs.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
rs.ContentType = "application/ms-excel";
rs.Write(excelStr);
rs.End();
}