在导出为csv文件时,正在使用文件名下载文件,且文件扩展名为MVC,但使用以下代码,
只有在部署到服务器后才能在本地正常工作。
public static KeyValuePair<string, string> ConvertDTtoExcel(DataTable dt, string filename)
{
string fileName = filename + ".csv";
string attachment = "attachment; filename=" + fileName;
HttpResponse response = HttpContext.Current.Response;
try
{
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", attachment);
response.ContentType = "application/csv";
response.ContentEncoding = System.Text.Encoding.UTF8;
string tab = string.Empty;
foreach (DataColumn dc in dt.Columns)
{
response.Write(tab + dc.ColumnName);
tab = ",";
}
response.Write(Environment.NewLine);
int newRow;
foreach (DataRow dr in dt.Rows)
{
tab = string.Empty;
for (newRow = 0; newRow < dt.Columns.Count; newRow++)
{
response.Write(tab + dr[newRow].ToString());
tab = ",";
}
response.Write(Environment.NewLine);
}
response.Flush();
response.End();
return new KeyValuePair<string, string>(fileName, response.ContentType);
}
catch (Exception ex)
{
Logger.Error(string.Format("Method Name: ConvertDTtoExcel, Error Occurred {0}", ex.ToString()));
throw;
}
finally
{
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}