匯出 Excel 功能

  • 88
  • 0

匯出 Excel 功能

 <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-2.0.0.min.js")"></script>//版本記得修改
    <script type="text/javascript">
        function exportExcel() {

            var sHtml = htmlEncode($("#MyTable")[0].outerHTML);//做html編碼 記得這個喔#MyTable

            $("input[name='hHtml']").val(sHtml);

            //表單提交
            $("form[name='myForm']").submit();
        }
        //↓出自:http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding
        function htmlEncode(value) {
            //create a in-memory div, set it's inner text(which jQuery automatically encodes)
            //then grab the encoded contents back out.  The div never exists on the page.
            return $('<div/>').text(value).html();
        }
    </script>
   <input type="button" value="匯出" onclick="exportExcel();" />

@using (Html.BeginForm("ExportExcel", "記得修改", FormMethod.Post, new { name="myForm"}))
{
    @Html.Hidden("hHtml")

}
[HttpPost]
        public ActionResult ExportExcel(FormCollection form)
        {

            string strHtml = form["hHtml"];
            strHtml = HttpUtility.HtmlDecode(strHtml);//Html解碼
            byte[] b = System.Text.Encoding.Default.GetBytes(strHtml);//字串轉byte陣列
            return File(b, "application/vnd.ms-excel", "這是Excel.xls");//輸出檔案給Client端
        }

https://dotblogs.com.tw/shadow/2013/05/15/104176