工程是一门科学,科学是严谨的。

excel、csv、txt文件数据读取

     /// <summary>
        /// 读取Excel表每一行第一列的字符串集合
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        private string[] ExcelReader(string filePath)
        {
            List<string> result = new List<string>();
            string connStr = "Provider=Microsoft.Ace.OleDb.12.0;data source=" + filePath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
            OleDbConnection Conn = new OleDbConnection(connStr);
            Conn.Open();
            DataTable dtTabeName = new DataTable();
            dtTabeName = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dtTabeName == null)
            {
                return null;
            }
            string SheetName = dtTabeName.Rows[0]["TABLE_NAME"].ToString();
            DataSet ds = new DataSet();
            OleDbDataAdapter odda = null;
            odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", SheetName), Conn);
            odda.Fill(ds, SheetName);
            Conn.Close();
            DataTable dt = ds.Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString().Trim().Length > 0)
                {
                    result.Add(dt.Rows[i][0].ToString());
                }
            }
            return result.ToArray();
        }

        /// <summary>
        /// 读取Csv\Txt文件中每一行第一列的字符串集合
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        private string[] CsvTxtReader(string filePath, string encoding = "gb2312")
        {
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding(encoding)))
            {
                sb.Append(sr.ReadToEnd());
            }
            string _text = sb.ToString();
            string[] separator = { "\r\n", "\n\r", "\n" };
            string[] _textArray = _text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            return _textArray;
        }

 

posted @ 2014-02-08 17:38  大圣的笑  阅读(876)  评论(0编辑  收藏  举报