大家好,今天跟大家學習 如何在匯出Excel檔案的功能。
Step 1. Controller 建立 Excel(要匯出的頁面)、ExcelExport(下載的頁面)
public ActionResult Excel()
{
return View();
}
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端
return View();
}
Step 2. View
Excel.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<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編碼
$("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>
</head>
<body>
<table width="100%" border="1" cellpadding="0" cellspacing="0" id="MyTable">
<thead>
<tr>
<th>編號</th>
<th>名稱</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>測試1</td>
</tr>
<tr>
<td>2</td>
<td>測試2</td>
</tr>
<tr>
<td>3</td>
<td>測試3</td>
</tr>
</tbody>
</table>
<br />
<input type="button" value="匯出" onclick="exportExcel();" />
</body>
</html>
@using (Html.BeginForm("ExportExcel", "Home", FormMethod.Post, new { name = "myForm" }))
{
@Html.Hidden("hHtml")
}
成功畫面
參考網址:
[ASP.net MVC 4] 把Html Table匯出Excel (簡易做法)