Exporting a Unicode CSV (Comma Separated) file to Excel 2003 or Excel 2007 causes all columns to end in the first Excel column
As Whose pointed out, localizations or changes in Excel options (list separator character) may cause incorrect behavior.
I recommend using Open XML for safer output.
Check out Create an Excel File in ASP.NET
source to share
If you use "," Excel 2007 will read it, but not 2003. And if you use ";", it's the other way around.
So, the best way is to create an html table and output it as .xls. Excel 2007 will ask if it has a reliable source.
Here's a sample code on how to do it:
private void ExportToXLSFromDataTable(DataTable dtExport, string filename)
{
StringBuilder dataToExport = new StringBuilder();
dataToExport.Append("<table>");
dataToExport.Append("<tr>");
foreach (DataColumn dCol in dtExport.Columns)
{
dataToExport.Append("<td>");
dataToExport.Append(Server.HtmlEncode(dCol.ColumnName));
dataToExport.Append("</td>");
}
dataToExport.Append("</tr>");
foreach (DataRow dRow in dtExport.Rows)
{
dataToExport.Append("<tr>");
foreach (object obj in dRow.ItemArray)
{
dataToExport.Append("<td>");
dataToExport.Append(Server.HtmlEncode(obj.ToString()));
dataToExport.Append("</td>");
}
dataToExport.Append("</tr>");
}
dataToExport.Append("</table>");
if (!string.IsNullOrEmpty(dataToExport.ToString()))
{
Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HttpContext.Current.Response.Write(dataToExport.ToString());
HttpContext.Current.Response.End();
}
}
source to share
Excel seems to be confused about the UTF-16 / UTF-8 byte order bytes, so try to get rid of them.
With CSV, the contents of cells can be a unicode character, but the separator, quote and newline characters must always be ASCII. You can think of CSV as ASCII as always, but each cell is a block of binary code and can be unicode text.
Also, take a look at http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm for more information.
source to share