简体   繁体   中英

datatable to Excel in c#

While exporting Datatable to Excel some columns to fall into a new line. I don't know what the problem is. My code is below:

string attachment = "attachment; filename=Test.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in transposedTable.Columns)
{
    Response.Write(tab + dc.ColumnName);
    //tab = "\t";
}
Response.Write("\t");
int i;
foreach (DataRow dr in transposedTable.Rows)
{
    Response.Write("\n");
    tab = "";
    for (i = 0; i < transposedTable.Columns.Count; i++)
    {
        Response.Write(tab + dr[i].ToString());
        tab = "\t";
    }
    Response.Write("\t");
}
Response.End();

I have tried many ways, but didn't get the exact issue. Is the issue with excel in machine or with my code?

It seems possible that your DataRow data contains newline characters, that is one reason why newlines might be appearing in your data.

Swapping:

    Response.Write(tab + dr[i].ToString());

For:

    string replacement = Regex.Replace(dr[i].ToString(), @"\t|\n|\r", "");
    Response.Write(tab + replacement);

May fix the problem if I did diagnose it correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM