1. 程式人生 > >C#讀取CSV檔案並儲存進資料庫

C#讀取CSV檔案並儲存進資料庫

   /// <summary>  
            /// 讀檔案  
            /// </summary>  
            /// <param name="path">檔案路徑</param>  
            /// <returns></returns>  
        internal void ReadFile(string Path)
        {
            try
            {
                FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.None);
                StreamReader sr = new StreamReader(fs, System.Text.UTF8Encoding.UTF8);
                InventorySql sql = new InventorySql();

                string str = "";
                string s = Console.ReadLine();
                int i = 0;
                while (str != null)
                {
                    str = sr.ReadLine();
                    if (str == null)
                        break;
                    string[] xu = new String[5];
                    xu = str.Split(',');
                    string F_Date = xu[0];
                    string F_Fax = xu[1].Replace("\"", "");//過濾雙引號
                    string F_ScanId = xu[2].Replace("\"", "");
                    string F_StoreNumber = xu[3];
                    string F_Num2 = xu[4];
                    DateTime time = DateTime.Now;
                    if (F_Fax == s)
                    {
                        Log.info(F_Fax); break;
                    }                   
                    if (i != 0)//過濾表頭
                    {
                        sql.Put("yearmonth", F_Date);
                        sql.Put("shop_no", F_Fax);
                        sql.Put("JAN", F_ScanId);
                        sql.Put("pro_count", F_StoreNumber);
                        sql.Put("real_count", F_Num2);
                        sql.Put("insert_time", time);
                        db.Execute(sql.GetSQL(InventorySql.InsertInventory)).ToString();
                    }
                    i++;
                }                
                sr.Close();
            }
            catch(Exception e)
            {
                throw new Exception(e.Message, e);
            }
        }