復制代碼 代碼如下:
/// <summary>
/// 將一組對象導出成EXCEL
/// </summary>
/// <typeparam>要導出對象的類型</typeparam>
/// <param>一組對象</param>
/// <param>導出后的文件名</param>
/// <param>列名信息</param>
public static 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<PropertyInfo> myPro = new List<PropertyInfo>();
foreach (string cName in columnInfo.Keys)
{
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 (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();
}
復制代碼 代碼如下:
/// <summary>
/// 將一組對象導出成EXCEL
/// </summary>
/// <typeparam>要導出對象的類型</typeparam>
/// <param>一組對象</param>
/// <param>導出后的文件名</param>
/// <param>列名信息</param>
public static void ExExcel<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(objList.Count * columnInfo.Count);
Type myType = objList[0].GetType();
//根據反射從傳遞進來的屬性名信息得到要顯示的屬性
List<PropertyInfo> myPro = new List<PropertyInfo>();
foreach (string cName in columnInfo.Keys)
{
PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
excelStr.Append(columnInfo[cName]).Append("/t");
}
}
//如果沒有找到可用的屬性則結束
if (myPro.Count == 0) { return; }
excelStr.Append("/n");
foreach (T obj in objList)
{
foreach (PropertyInfo p in myPro)
{
excelStr.Append(p.GetValue(obj, null)).Append("/t");
}
excelStr.Append("/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();
}
}
新聞熱點
疑難解答
圖片精選