导出为csv文件时,正在下载文件,但文件名不带扩展名MVC

时间:2018-07-23 15:15:48

标签: asp.net-mvc export-to-csv

在导出为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();
                }

            }

0 个答案:

没有答案