'StreamWriter writes all data into obe Column in CSV
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var mailClient = client)
using (var messagesd = msg)
{
foreach (DataColumn column in objDT.Columns)
{
writer.WriteLine(column.ColumnName);
}
writer.WriteLine();
for (int i = 0; i < objDT.Rows.Count; i++)
{
DataRow row = objDT.Rows[i];
for (int j = 0; j < row.ItemArray.Length; j++)
{
if (row.ItemArray[j] != null && !Convert.IsDBNull(row.ItemArray[j]))
{
writer.Write(row.ItemArray[j].ToString());
}
else
{
writer.Write("");
}
if (j < row.ItemArray.Length - 1)
{
writer.Write(",");
}
else if (i < objDT.Rows.Count - 1)
{
writer.WriteLine();
}
}
}
writer.Flush();
stream.Position = 0;
messagesd.Attachments.Add(new Attachment(stream, "test.csv"));
mailClient.Send(messagesd);
I have 3 columns, but result I`m getting:
testATestBTestC
under single column Result i want is TestA column 1, TestB column 2 and TestC column 3
Any help would be appreciated. Thank you.
Solution 1:[1]
You should write a delimeter(
,) after every value (header name or value) except last one. UseWritemethod to put values into a row andWriteLineto start a new row.It is better to use existing libraries from Nuget.
CSVHelperas example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
