Export to CSV using MVC, C# and jQuery

后端 未结 9 1041
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 13:42

I am trying to export a list to a CSV file. I got it all working up to the point I want to write to file to the response stream. This doesn\'t do anything.

Here is m

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 13:58

    From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';

    In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,

    using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                //Build the CSV file data as a Comma separated string.
                                string csv = string.Empty;
                                foreach (DataColumn column in dt.Columns)
                                {
                                    //Add the Header row for CSV file.
                                    csv += column.ColumnName + ',';
                                }
                                //Add new line.
                                csv += "\r\n";
                                foreach (DataRow row in dt.Rows)
                                {
                                    foreach (DataColumn column in dt.Columns)
                                    {
                                        //Add the Data rows.
                                        csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                                    }
                                    //Add new line.
                                    csv += "\r\n";
                                 }
                                 //Download the CSV file.
                                 Response.Clear();
                                 Response.Buffer = true;
                                 Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv");
                                 Response.Charset = "";
                                 //Response.ContentType = "application/text";
                                 Response.ContentType = "application/x-msexcel";
                                 Response.Output.Write(csv);
                                 Response.Flush();
                                 Response.End();
                               }
    

提交回复
热议问题