導出EXCEL是經常用到的功能,之前接觸過,最近又再次用到了,就總結下!
將以下方法寫在Action裏就好。
public ActionResult OutExcel()
{
string whereStr = "";
whereStr += string.Format("***");
IList<LLM.Model.****> List = BLL.GetModelList(whereStr);
string strHtml = "<meta http-equiv='content-type' content='application/ms-excel; charset=GB2312'/><table><tr>";
strHtml += "<td>***</td>" + "<td>***</td>" + "<td>***</td>" + "<td>***</td></td></tr><tr>";
foreach (LLM.Model.T_Base_Order model in orderList)
{
strHtml += "<td>" + model.***+ "</td>";
strHtml += "<td>" + model.***+ "</td>";
strHtml += "<td>" + model.***+ "</td>";
strHtml += "</tr>";
}
strHtml += "</table>";
strHtml = HttpUtility.HtmlDecode(strHtml);//Html解碼
byte[] b = System.Text.Encoding.Default.GetBytes(strHtml);//字串轉byte陣列
string filename = "***.xls";//文件名字
return File(b, "application/ms-excel", filename);//輸出檔案給Client端
}
比較簡單的比特流轉換Excel方法,通過瀏覽器解碼,簡單好用。