C#导入Excel|读取Excel方法总结

原文:http://www.sufeinet.com/thread-2029-1-1.html

1.  StreamReader 方法

这种方法一般不用,因为他读出来的是流,一般是转成字符串

代码如下:

  StreamReader sr = new StreamReader("文件名以及完整路径",System.Text.Encoding.Default);
            string data = sr.ReadToEnd();
            sr.Close();

2.OleDbConnection读取

最常 用的看下代码吧

  /**/
        /// <summary>
        /// 返回Excel数据源
        /// </summary>
        /// <param name="filename">文件路径</param>
        /// <param name="TSql">TSql</param>
        /// <returns>DataSet</returns>
        public static DataSet ExcelToDataSet(string filename, string TSql)
        {
            DataSet ds;
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filename;
            OleDbConnection myConn = new OleDbConnection(strCon);
            string strCom = TSql;
            myConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            ds = new DataSet();
            myCommand.Fill(ds);
            myConn.Close();
            return ds;
        }

         使用方法如下,只要写Sql语句就行了

//设置T_Sql
        string TSql = "SELECT  * FROM [sheel1$]";
        //读取数据
        DataTable table = ExcelToDataSet(fullPath, TSql).Tables[0];

 在这种情况下大家一般都会碰到这样的问题

如果是动态导入很多Excel表格的时候,他们的表名可能不一样,总不能每次都输入一次表名吧,其它不需要的

只要用下面的方法就可以得到表名

请看代码

 /// <summary>
        /// 动态取Excel表名
        /// </summary>
        /// <param name="fullPath">文件路径</param>
        /// <returns></returns>
        public static string GetExcelFirstTableName(string fullPath)
        {
            string tableName = null;
            if (File.Exists(fullPath))
            {
                using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet." +
                "OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + fullPath))
                {
                    conn.Open();
                    tableName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();
                }
            }

            return tableName;
        }

 修改上面的代码如下所示

 string tableName = GetExcelFirstTableName("文件 路径");
        //设置T_Sql
        string TSql = "SELECT  * FROM [" + tableName + "]";
        //读取数据
        DataTable table = ExcelToDataSet(fullPath, TSql).Tables[0];

 问题解决了

本人的博客不再维护从2013年就不再维护了 需要我帮助的朋友请到我的个人论坛 http://www.sufeinet.com 进行讨论,感谢大家对我的支持!
原文地址:https://www.cnblogs.com/sufei/p/2470262.html