2011年5月23日 星期一

C# 讀取 CSV 檔

直接將 Source Code 貼出來給你們參考

做法跟使用 ADO 方式一樣

說明請參考 Source Code 的註解就會明白了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace LoadCSVDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            OleDbConnection conn = null;
            OleDbCommand comm = null;
            OleDbDataReader dr = null;
            string sql = "select * from [TestData.csv]"; // TestData.csv <-- 想要載入的 CSV 檔檔名
            // Data Source 的參數表示想載入的 CSV 檔的路徑位置
            // Extended Properties 中
            // --> Text 表示要載入的檔案屬性屬於文字檔
            // --> HDR = NO 表示第一行的資料非標頭欄位
            // --> HDR = YES 表示第一行的資料為標頭欄位
            string connectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\;Extended Properties='Text;HDR=NO'";

            try
            {
                conn = new OleDbConnection(connectString);
                conn.Open();

                comm = conn.CreateCommand();
                comm.CommandText = sql;

                dr = comm.ExecuteReader();
                while (dr.Read())
                {

                    Console.WriteLine("{0}\t\t{1}\t\t{2}", dr[0], dr[1], dr[0]);

                }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                    conn.Close();
            }

            Console.Read();
        }
    }
}




不過當你的系統是 64 位元時, 會發生以下問題








因為Jet不支援 64 位元, 所以必需編譯成 32 位元
請修改建置-->平台目標-->選擇 x86













再執行程式

沒有留言:

張貼留言