直接上代碼
前端頁面:
<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();
}
}