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)找挑战了解,加群请写好技术方向。

posted @ 2013-01-25 10:23  挑战君王  阅读(8301)  评论(5编辑  收藏  举报