0

I wrote the following function:

    public void ExportTableData(DataTable dtdata)
    {
            string attach = "attachment;filename=report.csv";
            Response.ClearContent();
            Response.ContentEncoding = Encoding.GetEncoding(1255);
            Response.AddHeader("content-disposition", attach);
            Response.ContentType = "application/ms-excel";
            if (dtdata != null)
            {
                foreach (DataColumn dc in dtdata.Columns)
                {
                    Response.Write(dc.ColumnName + "\t");
                    //sep = ";";
                }
                Response.Write(System.Environment.NewLine);
                foreach (DataRow dr in dtdata.Rows)
                {
                    for (int i = 0; i < dtdata.Columns.Count; i++)
                    {
                        Response.Write(dr[i].ToString() + "\t");
                    }
                    Response.Write("\n");
                }
                Response.End();
            }
        }

It works fine, but the only problem is that the data is written is one column only. What am i doing wrong?

Meital
  • 17
  • 6
  • try using `\r\n` for a new line instead of simply `\n` – Hugues Stefanski Aug 27 '17 at 16:27
  • Also, you might want to use a StringBuilder to build your response for performance reasons, and use `String.Join` per column instead of looping yourself, this might save you some typing. – Hugues Stefanski Aug 27 '17 at 16:28
  • 2
    You have several problems with this code. You're trying to create a tab delimited file, but you haven't [told Excel that it's tab delimited](https://stackoverflow.com/questions/17953679). You're using the line feed character as a line separator, but in Windows we use a carriage return linefeed (`\r\n`). You're using an Excel mime type, even though you're providing a CSV file, not Excel. And the worst mistake: you're trying to manually create a character delimited file instead of using a purpose built library that will handle the nuances for you. – mason Aug 27 '17 at 16:30
  • As long as you mentioned csv, why not user comma instead of tab for a column separation? Both ways you have to import the file to excel and tell it specifically what the separator is. – Lamar Aug 27 '17 at 17:07

0 Answers0