C operates on instances of CSV file classes

  • 2021-01-25 07:51:28
  • OfStack

This article illustrates how C# manipulates CSV file classes. Share with you for your reference. The specific analysis is as follows:

This C# class is used to convert DataTable to CSV files and CSV files to DataTable. This class is ideal if you need to convert between CSV and DataTable.


using System.Data;
using System.IO;
namespace DotNet.Utilities
{
 /// <summary>
 /// CSV File conversion class 
 /// </summary>
 public static class CsvHelper
 {
  /// <summary>
  ///  Export report as Csv
  /// </summary>
  /// <param name="dt">DataTable</param>
  /// <param name="strFilePath"> Physical path </param>
  /// <param name="tableheader"> header </param>
  /// <param name="columname"> The field , A comma </param>
  public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
  {
   try
   {
    string strBufferLine = "";
    StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
    strmWriterObj.WriteLine(tableheader);
    strmWriterObj.WriteLine(columname);
    for (int i = 0; i < dt.Rows.Count; i++)
    {
     strBufferLine = "";
     for (int j = 0; j < dt.Columns.Count; j++)
     {
      if (j > 0)
       strBufferLine += ",";
      strBufferLine += dt.Rows[i][j].ToString();
     }
     strmWriterObj.WriteLine(strBufferLine);
    }
    strmWriterObj.Close();
    return true;
   }
   catch
   {
    return false;
   }
  }
  /// <summary>
  ///  will Csv Read in DataTable
  /// </summary>
  /// <param name="filePath">csv The file path </param>
  /// <param name="n"> According to the first n Line is a field title, The first n+1 The line is the beginning of the record </param>
  public static DataTable csv2dt(string filePath, int n, DataTable dt)
  {
   StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
   int i = 0, m = 0;
   reader.Peek();
   while (reader.Peek() > 0)
   {
    m = m + 1;
    string str = reader.ReadLine();
    if (m >= n + 1)
    {
     string[] split = str.Split(',');
     System.Data.DataRow dr = dt.NewRow();
     for (i = 0; i < split.Length; i++)
     {
      dr[i] = split[i];
     }
     dt.Rows.Add(dr);
    }
   }
   return dt;
  }
 }
}

I hope this article is helpful to your C# program design.


Related articles: