CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

csv helper is writing 1 to 12 datetime in different format and 13 to 24 in different datetime format using version 4.0.30319

Open Prashantpaliwal911 opened this issue 1 year ago • 1 comments

var textwriter = new StreamWriter(memoryStream);
{
    using (var csv = new CsvWriter(textwriter))
    {
        csv.Configuration.Delimiter = CsvColumnsDelimiter.ToString();
       
        foreach (DataColumn column in dataTable.Columns)
        {
            csv.WriteField(column.ColumnName);
        }
        csv.NextRecord();

        foreach (DataRow row in dataTable.Rows)
        {
            for (var i = 0; i < dataTable.Columns.Count; i++)
            {
                var dataType = dataTable.Columns[i].DataType;
                string cellValue;

                if (row[i] == null || row[i] == DBNull.Value)
                {
                    cellValue = string.Empty;
                    csv.WriteField(cellValue);
                    continue;
                }

                switch (Type.GetTypeCode(dataType))
                {
                    case TypeCode.DateTime:
                        cellValue = ((DateTime)row[i]).ToString("dd-MMM-yyyy HH:m:s tt", Thread.CurrentThread.CurrentCulture);
                        break;
                    //Decimal cell values are modified depends on the current culture.
                    case TypeCode.Decimal:
                        cellValue = decimal.TryParse(row[i].ToString().Trim(), out var decResult)
                            ? decResult.ToString("N10", Thread.CurrentThread.CurrentCulture).TrimEnd('0').TrimEnd(',').TrimEnd('.')
                            : string.Empty;
                        break;
                    default:
                        cellValue = Convert.ToString(row[i], Thread.CurrentThread.CurrentCulture);
                        break;
                }

                csv.WriteField(cellValue);
            }
            csv.NextRecord();
        }
    }
}

Screenshot 2024-05-14 192216

Prashantpaliwal911 avatar May 14 '24 13:05 Prashantpaliwal911

Can you write a full example that shows the problem? Meaning, it contains the input data. Also, we need to see the output in CSV text format, not Excel.

JoshClose avatar May 14 '24 14:05 JoshClose