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;
            }

  • 相关阅读:
    [原创]如何在Windows下安装Bugfree2.0.0.1
    [原创]网站性能优化利器之一"google page speed"
    [原创]下一代Web 应用程序安全性测试工具HP WebInspect简介
    [原创]微软软件项目管理Team Foundation Server之测试人员
    [原创]Yeepay网站安全测试漏洞之跨站脚本注入
    [原创]软件测试过程改进的内容和注意事项
    [原创]快钱99bill网站安全性测试漏洞之“跨站式脚本注入”
    马化腾内部讲座:让产品自己召唤人
    [转贴]可用性测试
    [原创]浅谈缺陷分析的意义和方法
  • 原文地址:https://www.cnblogs.com/skyay/p/5752846.html
Copyright © 2011-2022 走看看