MVC下用C#实现Excel导出

时间:2023-03-09 20:08:13
MVC下用C#实现Excel导出

Aspx页面脚本:

function exportxls() {

window.open("/Common/HomeExport?startdate=" + $("#hidStartTime").val(), "exportxls", null);

}

C#代码如下:

public class CommonController

{

public void HomeExport()

{

StringBuilder sHtml =
new StringBuilder(string.Empty);

//下面这句解决中文乱码

sHtml.Append("<meta
http-equiv=’content-type’
content=’application/ms-excel; charset=utf-8’/>");

……

//打印表头

sHtml.Append("<table
border=’1’ width=’100%’>");

//打印列名

sHtml.Append("<tr
height=’20’ align=’center’style='background-color:yellow'><td>No.
</td><td>Project</td><td>Content</td>tr>");

//循环读取List集合

……

//打印表尾

sHtml.Append("</table>");

string filename = "Report";

//调用输出Excel表的方法

ExportToExcel("application/ms-excel", filename +
".xls",
sHtml.ToString());

}

public void ExportToExcel(string FileType, string FileName, string ExcelContent)

{

System.Web.HttpContext.Current.Response.Charset =
"UTF-8";

System.Web.HttpContext.Current.Response.ContentEncoding
= System.Text.Encoding.UTF8;

System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=" +
HttpUtility.UrlEncode(FileName,
System.Text.Encoding.UTF8).ToString());

System.Web.HttpContext.Current.Response.ContentType =
FileType;

System.IO.StringWriter tw =
new System.IO.StringWriter();

System.Web.HttpContext.Current.Response.Output.Write(ExcelContent.ToString());

System.Web.HttpContext.Current.Response.Flush();

System.Web.HttpContext.Current.Response.End();

}

}