日期:2014-05-18  浏览次数:21027 次

如何在程序中列出Excel表的列名?
如何在程序中列出Excel表的列名?

------解决方案--------------------
首先程序识别此文件 找到标题行 对象思想解决。
------解决方案--------------------
OLEDB连接excel,然后select * from sheet1 where 1=0,把结果装到DataSet 中,然后循环取DataTable的column,column的name就是列名
------解决方案--------------------
C# code

 public IList<string> GetColumnsBySheet(string MyFullFileName, string MySheetName)
        {
            try
            {
                IList<String> fields = new List<String>();
                DataTable dt = GetSheetData(MyFullFileName,MySheetName);
                foreach (DataColumn dc in dt.Columns)
                {
                    fields.Add(dc.ColumnName);
                }
                fields.Insert(0, "Not In My File");
                return fields;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

       protected DataTable GetSheetData(string MyFullFileName,string MySheetName)
        {
            try
            {
                return GetSheetData(MyFullFileName,"select top 0 * from [" + MySheetName + "]");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

     protected DataTable GetSheetData(string MyFullFileName,string CmdString)
        {
            DataTable dt = null;
            OleDbConnection conn = new OleDbConnection();
            try
            {
                conn.ConnectionString = GetConnection(FullFileName);
                conn.Open();
                OleDbDataAdapter adp = new OleDbDataAdapter(CmdString, conn);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                dt = ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
            return dt;
        }

 protected string GetConnection(string MyFullFileName)
        {
            string cnn = string.Empty;
            switch (UpLoadFileType)
            { 
                case FileType.Access:
                    cnn= "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + MyFullFileName;
                    break;
                case FileType.Excel:
                    cnn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + MyFullFileName + "; Extended Properties=Excel 8.0";
                    break;
                case FileType.Text:
                    cnn = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + System.IO.Directory.GetParent(MyFullFileName).FullName + @";Extended Properties=""text;HDR=Yes;FMT=Delimited""";
                    break;
                default:
                    throw new Exception("FileType is Wrong!");
            }
            return cnn;
        }