导入CSV格式文件方法

  /// <summary>
        /// 导入CSV格式文件
        /// </summary>
        /// <param name="filePath">文件地址</param>
        /// <returns></returns>
protected DataTable GetFlowData(string filePath)
        {
            string strline;
            string[] aryline;
            bool blnFlag = true;
            DataTable dt = new DataTable();

            StreamReader mysr = new StreamReader(filePath, System.Text.Encoding.Default);
            try
            {
                int ColCount = 0;
                while ((strline = mysr.ReadLine()) != null)
                {

                    aryline = strline.Split(new char[] { ',' });
                    if (blnFlag)
                    {
                        blnFlag = false;
                        ColCount = aryline.Length;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            dt.Columns.Add(aryline[i]);
                        }
                        continue;
                    }
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < ColCount; i++)
                    {
                        dr[i] = aryline[i];
                    }
                    dt.Rows.Add(dr);

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mysr.Close();
                mysr.Dispose();
            }
            return dt;
        }
View Code

 

 

posted on 2013-09-10 13:39  WeiLight  阅读(537)  评论(0编辑  收藏  举报