简体   繁体   中英

Exporting DataTable to Excel remove line breaks

Hi I am using the code below to export a datatable to an excel file

string attachment = "attachment; filename=Data.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";

string tab = "";
foreach (DataColumn dc in dtDataForExport.Columns)
{
    Response.Write(tab + dc.ColumnName);
    tab = "\t";
}
Response.Write("\n");
int i;

foreach (DataRow dr in dtDataForExport.Rows)
{
    tab = "";
    for (i = 0; i < dtDataForExport.Columns.Count; i++)
    {
        string content = dr[i].ToString();
        content.Replace(System.Environment.NewLine, " ");
        Response.Write(tab + content);
        tab = "\t";
     }
     Response.Write("\n");
}
Response.End();

As you can see I have tried to a replace on System.Environment.NewLine but I am still getting linebreaks causing issues in the Excel Document does anyone have any suggestions to get rid of these?

Strings are immutable, that means you cannot modify them, that's why this doesn't work:

content.Replace(System.Environment.NewLine, " ");

You are not reassigning the string to your variable:

content = content.Replace(System.Environment.NewLine, " ");

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