excel, csv, txt 파일 데이터 읽기

6683 단어 Excel
     /// <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
", "
\r
", "
" }; string[] _textArray = _text.Split(separator, StringSplitOptions.RemoveEmptyEntries); return _textArray; }

좋은 웹페이지 즐겨찾기