In my application, I need to exporting datatable to CSV format file. I can do this with the following code except if the column is the string with leading zero suach as: 00254. After exporting to csv, I can see it display correct in Notepad but when open it by Excel, it lose all the leading zero: 00254 to 254 only.
Because datatable with some column is number such as : quantity and amount so we cannot convert all columns to string before export to CSV.
var dsx = new DataSet();
dsx = ProcessData_Export(dtc);
IEnumerable<string> columnNames = dsx.Tables[0].Columns
.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dsx.Tables[0].Rows)
{
IEnumerable<string> fields = row.ItemArray
.Select(field => Regex.Replace(field.ToString(), "\r\n", String.Empty));
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(pathDesktop + "\\" + exFileName, sb.ToString(), Encoding.UTF8);