直接上代码
前端页面:
<input type="button" id="btn_Export" value="导出CSV格式" οnclick="ExportCSV()" />
前端JS:
$.ajax({
url: "/Home/Export",
success: function (data)
{
alert(data);
}
});
控制器代码:
public string Export()
{
System.IO.MemoryStream output = new System.IO.MemoryStream();
string excelstr = "姓名,性别,年龄" + "\n";
//输出内容
for (int i = 0; i < 10; i++)
{
excelstr += "姓名"+i.ToString()+",性别"+i.ToString()+",年龄"+i.ToString() + "\n";
}
string filePhysicalPath = Server.MapPath("~/DataCsv/");
if (!Directory.Exists(filePhysicalPath))//判断上传文件夹是否存在,若不存在,则创建
{
Directory.CreateDirectory(filePhysicalPath);//创建文件夹
}
string url = Server.MapPath("~\\DataCsv\\") + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
StreamWriter sw = new StreamWriter(url, false, Encoding.GetEncoding("GB2312"));
try
{
sw.Write(excelstr);// 文件流写出
sw.Flush();//判断是否有文件,如果有则删除
sw.Dispose();//释放流的资源
return url;
}
catch (IOException ex)
{
return ex.Message.ToString();
}
}