日期:2014-05-18  浏览次数:20746 次

MVC3 Excel 导出
在MVC3的页面上,我开始是用js导出的Excel,
<script type="text/javascript">
  function exportTableToExcel(table_id) {
  alert("1");
  var o_AXO = new ActiveXObject("Excel.Application");
  alert("2");
  var o_WB;
  var o_Sheet;
  try {
  o_WB = o_AXO.Workbooks.Add();
  //激活当前sheet
  o_Sheet = o_WB.ActiveSheet;
  } catch (err) {
  alert("同时请确认已经安装好Excel软件");
  return false;
  }
  var o_table = document.getElementById(table_id);
  var row_len = o_table.rows.length;
  for (i = 0; i < row_len; i++) {
  var cell_len = o_table.rows[i].cells.length;
  for (j = 0; j < cell_len; j++) {
  var cellText = o_table.rows[i].cells[j].innerText;
  o_Sheet.Cells(i + 1, j + 1).value = cellText;  
  }
  }
  o_AXO.Visible = true;
   
  }
</script>但是换了台机子就不行了, var o_AXO = new ActiveXObject("Excel.Application");这句话不能执行了,以前是可以的,页面有一个table表,但是分页的就不行了,只能导出当前页面,请问JS能处理分页的导出吗,还有一种做法是后台导出,谁能给个成功的例子,要是MVC3的环境下,谢谢!!

------解决方案--------------------
C# code
 /// <summary>
        /// 导出Grid的数据(全部)到Excel
        /// 字段全部为BoundField类型时可用
        /// 要是字段为TemplateField模板型时就取不到数据
        /// </summary>
        /// <param name="grid">grid的ID</param>
        /// <param name="dt">数据源</param>
        /// <param name="excelFileName">要导出Excel的文件名</param>
        public static void OutputExcel(GridView grid, DataTable dt, string excelFileName)
        {
            Page page = (Page)HttpContext.Current.Handler;
            page.Response.Clear();
            string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));
            page.Response.AddHeader("Content-Disposition", "attachment:filename=" + fileName + ".xls");
            page.Response.ContentType = "application/vnd.ms-excel";
            page.Response.Charset = "utf-8";

            StringBuilder s = new StringBuilder();
            s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");

            int count = grid.Columns.Count;

            s.Append("<table border=1>");
            s.AppendLine("<tr>");
            for (int i = 0; i < count; i++)
            {

                if (grid.Columns[i].GetType() == typeof(BoundField))
                    s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");

                //s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");

            }
            s.Append("</tr>");

            foreach (DataRow dr in dt.Rows)
            {
                s.AppendLine("<tr>");
                for (int n = 0; n < count; n++)
                {
                    if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
                        s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>");

                }
                s.AppendLine("</tr>");
            }

            s.Append("</table>");
            s.Append("</body></html&g