-1

enter image description here

I want to convert my data table into this csv format.Please help me if anyone have idea how to do that

this is what I have tried.

  StringBuilder data = new StringBuilder();
            for (int row = 0; row < dataTable.Rows.Count; row++)
            {
                data.Append(Environment.NewLine);
                data.Append(dataTable.Rows[row]["Group"]);
                data.Append(Environment.NewLine);

                for (int column = 0; column < dataTable.Columns.Count; column++)
                {
                   

                    if (column == dataTable.Columns.Count - 1)
                        data.Append(dataTable.Rows[row][column].ToString().Replace(",", ";"));
                    else
                        data.Append(dataTable.Rows[row][column].ToString().Replace(",", ";") + ',');
                }

}

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236

1 Answers1

0

I suppose that you have data table column like this: TN_USERNAME | TN_NAME | TN_USERTYPE | CH_USERNAME | ...

StringBuilder data = new StringBuilder();

//add header for csv file in string builder object (column names)
for(int column = 0; column < dataTable.Columns.Count; column++)
{
    data.Append(dataTable.Columns[column].Name);
    if(column != dataTable.Columns.Count - 1) //last column doesn't ends with ;
        data.Append(";")
}

data.AppendLine();

for (int row = 0; row < dataTable.Rows.Count; row++)
{

    for (int column = 0; column < dataTable.Columns.Count; column++)
    {
        if (column == dataTable.Columns.Count - 1)
            data.Append(dataTable.Rows[row][column].ToString());
        else
            data.Append(dataTable.Rows[row][column].ToString()).Append(";");
    }

    data.AppendLine();
}
TJacken
  • 354
  • 3
  • 12
  • CSV doesn't have merged cells and borders, or multiple header lines. What the OP posted is a report rendered as a text, with layout, centered text and borders – Panagiotis Kanavos Sep 01 '20 at 13:05
  • @PanagiotisKanavos I know that CSV doesn't have merged cells and borders, from his post I thought he want to create csv file from datatable, as you wrote on his post he would need to create excel file. – TJacken Sep 01 '20 at 13:11
  • That's why posting links to images instead of putting them in the question itself is discouraged. The question is misleading – Panagiotis Kanavos Sep 01 '20 at 13:19