日期:2014-05-18 浏览次数:21027 次
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; }