ASP.NET MVC 导出CSV文件
ASP.NET MVC 导出CSV文件、直接贴代码
/// <summary>
/// ASP.NET MVC导出CSV文件Demo1
/// </summary>
/// <returns></returns>
public ActionResult ExportDemo1()
{
System.IO.MemoryStream output = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(output, System.Text.Encoding.UTF8);
writer.Write("姓名,性别,年龄");//输出标题,逗号分割(注意最后一列不加逗号)
writer.WriteLine();
//输出内容
for (int i = 0; i < 10; i++)
{
writer.Write("用户" + i + ",\"");//第一列
writer.Write("男\",\"");//中间列
writer.Write("20\",");//最后一列
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "demo1.csv");
}
/// <summary>
/// ASP.NET MVC导出CSV文件Demo2
/// </summary>
/// <returns></returns>
public ActionResult ExportDemo2()
{
//定义模版(标题、内容字段、格式化参数)
string[,] template = new string[,] {
{ "姓名,", "Name" ,"{0}"}
, { "性别,", "Sex","{0}" }
, { "年龄", "Age" ,"{0}"}
};
System.IO.MemoryStream output = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(output, System.Text.Encoding.UTF8);
//输出标题
int lenght = template.GetLength(0);
for (int i = 0; i < lenght; i++)
writer.Write(template[i, 0]);
writer.WriteLine();
//输出内容
List<User> lstUser = GetUsers();
if (lstUser != null)
{
foreach (User user in lstUser)
{
for (int i = 0; i < lenght; i++)
{
writer.Write(string.Format(template[i, 2]
, user.GetType().GetProperty(template[i, 1]).GetValue(user, null)));
if (i == 0)
writer.Write(",\"");
else if (i == lenght - 1)
writer.WriteLine();
else if (i == lenght - 2)
writer.Write("\",");
else
writer.Write("\",\"");
}
}
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "demo2.csv");
}
http://blog.csdn.net/moyanruo/article/details/18699081
http://blog.csdn.net/binyao02123202/article/details/6865033
ashx 页面:
StringWriter writer = new StringWriter(); //输出内容
for (int i = 0; i < 10; i++)
{
writer.Write("用户" + i + ",\"");//第一列
writer.Write("男\",\"");//中间列
writer.Write("20\",");//最后一列
writer.WriteLine();
}
writer.Close();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.Write(writer);
HttpContext.Current.Response.End();
JS 导出方法
$("#SearchTitle").click(function () {
var url= UrlBase + 'Admin/Activity/Export';
window.open(url);
}