C#操作CSV檔案類執行個體

來源:互聯網
上載者:User

標籤:mes   href   檔案路徑   csv   otn   逗號   wro   osg   splay   

本文執行個體講述了C#操作CSV檔案類。分享給大家供大家參考。具體分析如下:

這個C#類用於轉換DataTable為CSV檔案、CSV檔案轉換成DataTable,如果需要進行CSV和DataTable之間進行轉換,使用這個類非常合適。

using System.Data;using System.IO;namespace DotNet.Utilities{ /// <summary> /// CSV檔案轉換類 /// </summary> public static class CsvHelper {  /// <summary>  /// 匯出報表為Csv  /// </summary>  /// <param name="dt">DataTable</param>  /// <param name="strFilePath">實體路徑</param>  /// <param name="tableheader">表頭</param>  /// <param name="columname">欄位標題,逗號分隔</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>  /// 將Csv讀入DataTable  /// </summary>  /// <param name="filePath">csv檔案路徑</param>  /// <param name="n">表示第n行是欄位title,第n+1行是記錄開始</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;  } }}

希望本文所述對大家的C#程式設計有所協助。

除聲明外, 跑步客文章均為原創,轉載請以連結形式標明本文地址
  C#操作CSV檔案類執行個體

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23064.html






相關內容C#自訂事件之屬性改變引發事件樣本C#視頻轉換類分享詳細解析C#多線程同步事件及等待控制代碼C#異常處理中try和catch語句及finally語句的用法樣本
C# readnodefile()不能讀取帶有檔案名稱為漢字的osg檔案解決方案如何在datatable中使用groupby進行分組統計Winform實現抓取web頁面內容的方法DevExpress實現為TextEdit設定浮水印文字的方法

C#操作CSV檔案類執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.