在Discovery.End()中将Datatable转换为Csv有一些问题

时间:2014-07-22 05:31:38

标签: c# asp.net csv response

我正在尝试将datatable转换为csv格式。代码正常工作并正确获取csv。但问题是在Response.End()之后有一些异常显示了catch块;

这是我的代码

 public void GetCSV(DataTable dt)
    {
        StringBuilder sb = new StringBuilder();
        IEnumerable<string> columnNames1 = dt.Columns.Cast<DataColumn>().
            Select(column => column.ColumnName);
        sb.AppendLine(string.Join(",", columnNames1));
        foreach (DataRow row in dt.Rows)
        {
            IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
            foreach (var item in fields)
            {
                sb.AppendFormat("\"{0}\",", item.Replace("\"", "\"\""));
            }
            sb = sb.Remove(sb.Length - 1, 1);
            sb.Append("\n");
            //sb.AppendLine(string.Join(",", fields));
        }

        string attachment1 = "attachment; filename=Application_Data.csv";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment1);
        Response.ContentType = "application/csv;charset=utf-8";
        Response.Charset = "utf-8";
        Response.Write(sb.ToString());
        Response.End();
    }

我只是调试并检查。然后Response.End有问题 显示的错误是 Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

任何人都可以知道这是什么问题。谢谢你提前寻求帮助。

2 个答案:

答案 0 :(得分:2)

试试这个

public void ExportToCSVFile(DataTable dt, string file_name)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
             "attachment;filename='" + file_name + "'.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                sb.Append(dt.Columns[k].ColumnName + ',');
            }
            sb.Append("\r\n");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    sb.Append(dt.Rows[i][k].ToString() + ',');
                }
                sb.Append("\r\n");
            }
            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

在此函数中传递数据表和文件名。

答案 1 :(得分:1)

var lines = new List<string>();

string[] columnNames = dataTable.Columns.Cast<datacolumn>().
                                  Select(column => column.ColumnName).
                                  ToArray();

var header = string.Join(",", columnNames);
lines.Add(header);

var valueLines = dt.AsEnumerable()
                   .Select(row => string.Join(",", row.ItemArray));            
lines.AddRange(valueLines );

File.WriteAllLines("excel.csv",lines);</datacolumn></string>