zoukankan      html  css  js  c++  java
  • C#中获取Excel文件的第一个表名

    //    2.以数据库方式打开并输入数据
    //      此方式将xls文件所在目录看作数据库,其中的xls文件看作数据库表,表名即文件名(不加扩展名)。
    //      函数importExcelToDataSet(string FilePath,string sheet)功能:从xls中读出数据到DataSet中,并返回DataSet对象。

            private DataSet importExcelToDataSet(string FilePath/*即文件目录的路径*/, string sheet/*表名即文件名(不加扩展名)*/)
            {

                string strConn;

                string getsheet;

                getsheet = "SELECT * FROM [" + sheet + "]" ;

                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";Extended Properties=Excel 8.0;";

                OleDbConnection conn = new OleDbConnection(strConn);

                OleDbDataAdapter myCommand = new OleDbDataAdapter(getsheet, strConn);

                DataSet myDataSet = new DataSet();

                try
                {

                    myCommand.Fill(myDataSet);

                }

                catch (Exception ex)
                {

                    MessageBox.Show("该Excel文件的工作表的名字不正确," + ex.Message);

                }

                return myDataSet;

            }


            /// <summary>
            /// C#中获取Excel文件的第一个表名 
            /// Excel文件中第一个表名的缺省值是Sheet1$, 但有时也会被改变为其他名字. 如果需要在C#中使用OleDb读写Excel文件, 就需要知道这个名字是什么. 以下代码就是实现这个功能的:
            /// </summary>
            /// <param name="excelFileName"></param>
            /// <returns></returns>
            public static string GetExcelFirstTableName(string excelFileName)
            {
                string tableName = null;
                if (File.Exists(excelFileName))
                {
                    using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet." +
                      "OLEDB.4.0;Extended Properties="Excel 8.0";Data Source=" + excelFileName))
                    {
                        conn.Open();
                        DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        tableName = dt.Rows[0][2].ToString().Trim();
                    }
                }
                return tableName;
            }

  • 相关阅读:
    【转】svn冲突问题详解 SVN版本冲突解决详解
    【转】Mysql解决The total number of locks exceeds the lock table size错误
    【转】iOS中修改AVPlayer的请求头信息
    【转】AJAX请求和普通HTTP请求区别
    【转】怎么给javascript + div编辑框光标位置插入表情文字等?
    【转】iOS开发笔记--识别单击还是双击
    【转】Android hdpi ldpi mdpi xhdpi xxhdpi适配详解
    87. Scramble String
    86. Partition List
    85. Maximal Rectangle
  • 原文地址:https://www.cnblogs.com/skyay/p/5752846.html
Copyright © 2011-2022 走看看