Reputation: 43
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?
Upvotes: 0
Views: 221
Reputation: 560
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.
Upvotes: 1