一、准备工作
下载MyXls 下载地址为:http://sourceforge.net/projects/myxls/
二、将下载的DLL添加到项目引用中。
三、开始写代码……
1.在Controllers里面相应的Controllers添加一个Action。
/// <summary>
/// 下载Action
/// </summary>
/// <returns></returns>
/// 创建人:JackYang
/// 2011/11/3
public ActionResult Down()
{XlsDocument xls = new XlsDocument();
Worksheet sheet = xls.Workbook.Worksheets.Add("下载内容");
ColumnInfo colInfo = new ColumnInfo(xls, sheet);
//将拼写好的Excel,转化成byte[]
return File(DownLoadHelper(xls,sheet,"下载内容"), "application/vnd.ms-excel");}
2.添加一个Excel进行二进制的转换的私有方法
/// <summary>
/// 将拼写好的Excel,转化成byte[]
/// </summary>
/// <param name="xls">XLS.</param>
/// <param name="sheet">sheet.</param>
/// <param name="xlsName">下载时文件名称</param>
/// <returns></returns>
/// 创建人:JackYang
/// 2011/11/3
private byte[] DownLoadHelper(XlsDocument xls, Worksheet sheet, string xlsName){using (MemoryStream ms = new MemoryStream()){xls.Save(ms);ms.Flush();ms.Position = 0;sheet = null;
xls = null;
HttpResponse response = System.Web.HttpContext.Current.Response;response.Clear();response.Charset = "UTF-8";
response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + HttpUtility.UrlEncode(xlsName)));byte[] data = ms.ToArray();
return data;
}}
3.在前台页面,添加一个超链接,来调用这个Action。
@Html.ActionLink("下载", "Down");
四、OK了,点下,就可以下载到传说中正统的Excel文件了。