ASP.NET 從List匯出Excel

來源:互聯網
上載者:User

此方法有一個弊端, 就是必須將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();
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.