C# Mvc導出Excel表格


先把代碼貼出來:

public void Print()
  {
    //接收需要導出的數據
    List<實體類名稱> list = db.findAll<實體類名稱>();
 
    //命名導出表格的StringBuilder變量
    StringBuilder sHtml = new StringBuilder(string.Empty);
 
    //打印表頭
    sHtml.Append("<table border=\"1\" width=\"100%\">");
    sHtml.Append("<tr height=\"40\"><td colspan=\"5\" align=\"center\" style='font-size:24px'><b>XXXXXXX報價表" + "</b></td></tr>");
 
    //打印列名
    sHtml.Append("<tr height=\"20\" align=\"center\" style='background-color:#CD0000'><td>編號</td><td>商品名稱</td><td>市場價</td><td>VIP價格</td><td>說明</td></tr>");
    
    //循環讀取List集合 
    for (int i = 0; i < list.Count; i++)
      {
         sHtml.Append("<tr height=\"20\" align=\"left\"><td style='background-color:#8DEEEE'>" + list[i].Id + "</td><td>" + list[i].Title + "</td><td style='background-color:#8DEEEE'>¥" + list[i].SalePrice + "</td><td style='color:#F00;background-color:#8DEEEE;'>¥" + list[i].VipPrice + "</td><td>" + list[i].Summary + "</td></tr>");
       }
 
     //打印表尾
     sHtml.Append("<tr height=\"40\"><td align=\"center\" colspan=\"5\" style='background-color:#CD0000;font-size:24px'><b>XXXXXXXX</a> </b></td></tr>");
     sHtml.Append("</table>");
 
     //調用輸出Excel表的方法
     ExportToExcel("application/ms-excel", "XXXXXX報價表.xls", sHtml.ToString()); 
}

 

 1 //輸入HTTP頭,然后把指定的流輸出到指定的文件名,然后指定文件類型
 2 public void ExportToExcel(string FileType, string FileName, string ExcelContent)
 3 {
 4     System.Web.HttpContext.Current.Response.ContentType = FileType;
 5     System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
 6     System.Web.HttpContext.Current.Response.Charset = "utf-8";
 7     System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
 8 
 9     System.IO.StringWriter tw = new System.IO.StringWriter();
10     System.Web.HttpContext.Current.Response.Output.Write(ExcelContent.ToString());
11     /*亂碼BUG修改 20140505*/
12     //如果采用以上代碼導出時出現內容亂碼,可將以下所注釋的代碼覆蓋掉上面【System.Web.HttpContext.Current.Response.Output.Write(ExcelContent.ToString());】即可實現。
13     //System.Web.HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>" + ExcelContent.ToString());
14     System.Web.HttpContext.Current.Response.Flush();
15     System.Web.HttpContext.Current.Response.End();
16 }
打印表格的方法

 

 

代碼已經解釋的很詳細,如果還有不懂可加群:攀登者IT【.Net】精英(172663374)找挑戰了解,加群請寫好技術方向。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM