日期:2014-05-17  浏览次数:20467 次

在ASP.NET MVC2 中导出excel
目前开发环境是:vs2010 ASP.NET MVC2 ,想在MVC中导出Excel,方式无所谓,我可以传一个dataTable或者dataSet,说白了就是在mvc2中实现dataTable或者dataSet导出Excel。(以前在普通的asp.net项目中也开发过类似导出的功能,但是在MVC中貌似不同),请做过类似功能的把源代码粘贴出来,包括引用什么命名空间?在线等,比较急,遇到合适答案马上结贴给分。谢谢!

------解决方案--------------------
给个例子吧,希望对你有帮助。
#region 导出用户信息到Excel
/// <summary>
/// 导出用户信息到Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExcelOut_Click(object sender, EventArgs e)
{
T_SYS_UserBLL userBll = new T_SYS_UserBLL();

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "GB2312";
Page.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//使输出的中文不乱码
string FileName = "人员导出Execel" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
Response.AppendHeader("Content-Disposition", "attachment;filename= " + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html;charset=GB2312\"><title>Copyright by SDU</title></head><body><form runat=server id=b1>");
Response.Write("<table border='1' cellpadding='0' cellspacing='0'><tr><td width='280' hight='40' align=\"center\"><strong>用户编号</strong>"
+ "</td><td width='140' align=\"center\"><strong>用户姓名</strong></td><td width='140' align=\"center\"><strong>用户登录名</strong>"
+ "</td><td width='140' align=\"center\"><strong>用户性别</strong></td><td width='140' align=\"center\"><strong>用户QQ</strong>"
+ "</td><td width='140' align=\"center\"><strong>用户手机</strong></td><td width='140' align=\"center\"><strong>用户状态</strong>"
+ "<td width='140' align=\"center\"><strong>用户备注</strong></td></tr>");


DataSet ds = userBll.GetUserInfoList("");

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string userID = ds.Tables[0].Rows[i]["User_ID"].ToString(); //用户编号
string loginName = ds.Tables[0].Rows[i]["User_LoginName"].ToString(); //用户登录名
string realName = ds.Tables[0].Rows[i]["User_RealName"].ToString(); //用户登录名

string userSex = ""; //用户性别
int Sex = Convert.ToInt32(ds.Tables[0].Rows[i]["User_SEX"]);
if (Sex == 1)
{
userSex = "男";
}
else if (Sex == 0)
{
userSex = "女";
}

string userQQ = ds.Tables[0].Rows[i]["User_QQ"].ToString();
string mobile = ds.Tables[0].Rows[i]["User_Mobile"].ToString();
string userStatus = "";
int status = Convert.ToInt32(ds.Tables[0].Rows[i]["User_Status"]);
if (status == 1)
{
userStatus = "已停用";
}
else if (status == 0)
{
userStatus = "正常";
}
string userDes = ds.Tables[0].Rows[i]["User_Des"].ToStri