アットウィキロゴ

csharp_csv

CSVを扱うクラス


public class CSVOperate
{
    #region 変数
    private System.Data.DataTable dt = new DataTable();
    private System.Data.OleDb.OleDbDataAdapter da = null;
    private int iRowLength = 0;
    private int iColLength = 0;
    #endregion
 
    #region プロパティ
    /// <summary>
    /// 行数
    /// </summary>
    public int RowLength
    {
        set { this.iRowLength = value; }
        get { return this.iRowLength; }
    }
 
    /// <summary>
    /// 列数
    /// </summary>
    public int ColLength
    {
        set { this.iColLength = value; }
        get { return this.iColLength; }
    }
    #endregion
 
    #region コンストラクタ
    /// <summary>
    /// コンストラクタ
    /// </summary>
    /// <param name="csvPath">CSVファイルパス(ヘッダー無しのCSV対象)</param>
    public CSVOperate(string csvPath)
    {
        string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
 
        // 作業フォルダをCSVのあるフォルダに設定
        if (Directory.Exists(System.IO.Path.GetDirectoryName(csvPath)))
            System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(csvPath));
 
        //接続
        string conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
            + @"." + ";Extended Properties=\"text;HDR=NO;FMT=Delimited\"";
        System.Data.OleDb.OleDbConnection con =
            new System.Data.OleDb.OleDbConnection(conString);
 
        string commText = "SELECT * FROM [" + System.IO.Path.GetFileName(csvPath) + "]";
        this.da = new System.Data.OleDb.OleDbDataAdapter(commText, con);
 
        //DataTableに格納する
        this.da.Fill(this.dt);
 
        // 行数を格納
        this.iRowLength = dt.Rows.Count;
        // 列数を格納
        this.iColLength = dt.Columns.Count;
 
        // 作業フォルダをアプリケーション実行フォルダに戻す
        System.IO.Directory.SetCurrentDirectory(baseDirectory);
    }
    #endregion
 
    #region メソッド
    /// <summary>
    /// 指定行列の値を取得する
    /// </summary>
    /// <param name="rowIdx">行インデクス</param>
    /// <param name="colIdx">列インデクス</param>
    /// <returns>指定行列の値</returns>
    public string getValue(int rowIdx, int colIdx)
    {
        if (rowIdx < 0 || colIdx < 0 || this.iRowLength < rowIdx || this.iColLength < colIdx)
            throw new ArgumentException(String.Format("指定されたインデクスは不正です。ROW={0},COL={1}", rowIdx, colIdx));
 
        return dt.Rows[rowIdx][colIdx].ToString();
    }
    #endregion
}
 
最終更新:2010年04月16日 16:38