1

I am trying to insert datatable contents into csv file and the below code doesn't work.

CODE:

System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
System.Data.DataRow newRow = dt.NewRow();
newRow["Name"] = str1;
newRow["Property"] = str2;
dt.Rows.Add(newRow);
dt.WriteToCsvFile("../../Data.csv");    

public static void WriteToCsvFile(this DataTable dataTable, string filePath)
    {
        StringBuilder fileContent = new StringBuilder();

        foreach (var col in dataTable.Columns)
        {
            fileContent.Append(col.ToString() + ",");
        }
        fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows)
        {
            foreach (var column in dr.ItemArray)
            {
                fileContent.Append("\"" + column.ToString() + "\",");
            }
            fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);
        }
        System.IO.File.WriteAllText(filePath, fileContent.ToString());
    }

Data.csv file is placed inside a project folder and the values are not getting added.

Really appreciate any suggestions on this.

Edit1:

dt.CreateCSVFile("../../Data.csv");

public static void CreateCSVFile(this DataTable dt, string strFilePath)
    {
        StreamWriter sw = new StreamWriter(strFilePath, true);

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }
6
  • 1
    take a look : stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv Commented Nov 15, 2016 at 6:18
  • "code doesn't work" isn't too helpful sadly Commented Nov 15, 2016 at 6:19
  • its working on my system. Did you place WriteToCsvFile in a static class? WriteToCsvFile is an extension method. It should be in a static class Commented Nov 15, 2016 at 6:23
  • @AksheyBhat - yes WriteToCsvFile is inside a static class. Commented Nov 15, 2016 at 6:26
  • Why asp.net tag? Is it web app or win app? Commented Nov 15, 2016 at 8:45

3 Answers 3

1

I don't know why you can use

dt.WriteToCsvFile("../../Data.csv"); 

there should be no this method in DataTable, if you want to convert DataTable to CVS, you can try the below:

public static string DataTableToCSV(this DataTable datatable, char seperator)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < datatable.Columns.Count; i++)
    {
        sb.Append(datatable.Columns[i]);
        if (i < datatable.Columns.Count - 1)
            sb.Append(seperator);
    }
    sb.AppendLine();
    foreach (DataRow dr in datatable.Rows)
    {
        for (int i = 0; i < datatable.Columns.Count; i++)
        {
            sb.Append(dr[i].ToString());

            if (i < datatable.Columns.Count - 1)
                sb.Append(seperator);
        }
        sb.AppendLine();
    }
    return sb.ToString();
}

you can find more in here

after call that method, you can save the string to file as below:

var contents = dt.DataTableToCSV(',');
System.IO.File.WriteAllText (@"D:\exportfile.cvs", contents);
Sign up to request clarification or add additional context in comments.

5 Comments

How can I write the contents to csv with this method?
sorry, what's contents? you just need to pass the DataTable object in it should be ok, and the seperator set to a comma
how can I give the filename path.
after run this method, you can get a string of cvs, and you just need to save these into a file is ok, please see my other answer
I tried this and it doesn't write the contents to CSV. I updated my post and that code works fine, but it doesn't align properly.
0

Here i converted the DataTable to CSV list. you can save it to file.

Code :

public static IEnumerable<string> ToCsvList(this DataTable table)
    {
        List<string> returnList = new List<string>();

        string colmn = string.Join(",", table.Columns.OfType<DataColumn>().Select(c => c.ColumnName));
        returnList.Add(colmn);

        foreach (DataRow row in table.Rows)
        {
            returnList.Add(string.Join(",", row.ItemArray));
        }

        return returnList;
    }

Comments

0

Hope this will help you sorry for not rewriting your code

 using (MemoryStream output = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(Server.MapPath("~/CSV/export.csv")))
            {


                writer.WriteLine(" OVERVIEW");
                writer.WriteLine("");
                writer.WriteLine("date : " + DateTimeOffset.Parse(DateTimeOffset.Now.ToString(), CultureInfo.CurrentCulture).ToString("yyyy-MM-dd"));

                writer.WriteLine("Name");
                writer.WriteLine("Property");

                writer.WriteLine("");
                writer.WriteLine("");





                writer.WriteLine("Name,Property");

                foreach (var item in List)
                {
                    writer.WriteLine(string.Format("{0},{1}",
                                               item.Name,
                                               item.Property


                                               ));
                }
                writer.Flush();
                output.Position = 0;
                // var document=Server.MapPath("~/Content/ExportedFiles/Exported_Users.csv");
            }


        }

5 Comments

I updated my post. I am using streamwriter to write the contents and it works just fine. But the problem is with the alignments, since the values are not placed property to particular column, they get breaked and are misplaced widely. FYI, these actions are performed in windows app.
@AlexanderPetrov could you please tell me why this is not a valid csv
Your code writes the string "overview" and empty strings - this breaks the csv format.
@AlexanderPetrov will it be a valid one if we removed writer.WriteLine(" OVERVIEW"); writer.WriteLine(""); writer.WriteLine("date : " + DateTimeOffset.Parse(DateTimeOffset.Now.ToString(), CultureInfo.CurrentCulture).ToString("yyyy-MM-dd")); writer.WriteLine("Name"); writer.WriteLine("Property"); writer.WriteLine(""); writer.WriteLine(""); this section
@vicky if your are looking for alignment better go for any library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.