Sylloge
A C# helper library
code/Data/Excel.cs
Go to the documentation of this file.
00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 using System;
00018 using System.Collections.Generic;
00019 using System.Text;
00020 using System.Data;
00021 using System.Reflection;
00022 using System.Data.OleDb;
00023 using System.Windows.Forms;
00024 
00025 namespace Sylloge.Data
00026 {
00031    public static class Excel
00032    {
00033       #region Events
00034 
00035       // Add any custom events here
00036 
00037       #endregion
00038 
00039       #region Constants
00040 
00044       public const string DEFAULT_EXCELNAME = "default.xls";
00045 
00046       #endregion
00047 
00048       #region Local Attributes
00049 
00050       private static OleDbDataAdapter Adapter { get; set; }
00051       private static OleDbConnection Conn { get; set; }
00052       public static DataSet Dataset { get; set; }
00053       private static bool IsOpen { get; set; }
00054       private static DataTable Table { get; set; }
00055 
00056       #endregion
00057 
00058       #region Class Methods and Properties
00059 
00060       public static void Dispose()
00061       {
00062          Excel.Close();
00063       }
00064 
00068       private static void CreateNewInstances()
00069       {
00070          Excel.Adapter = new OleDbDataAdapter();
00071          Excel.Conn = new OleDbConnection();
00072          Excel.Adapter.DeleteCommand = new OleDbCommand();
00073          Excel.Adapter.InsertCommand = new OleDbCommand();
00074          Excel.Adapter.SelectCommand = new OleDbCommand();
00075          Excel.Adapter.UpdateCommand = new OleDbCommand();
00076          Excel.Dataset = new DataSet();
00077          Excel.Table = new DataTable();
00078       }
00079 
00083       public static void Close()
00084       {
00085          if (Conn != null) { Conn.Close(); Conn.Dispose(); }
00086          if (Adapter != null) { Adapter.Dispose(); }
00087          if (Dataset != null) { Dataset.Dispose(); }
00088          if (Table != null) { Table.Dispose(); }
00089          Adapter = null;
00090          Dataset = null;
00091          Conn = null;
00092          Table = null;
00093          IsOpen = false;
00094       }
00095       
00101       public static DataTable GetDataFromFile(string fileName)
00102       {
00103          return Excel.GetDataFromFile(fileName, true, 0);
00104       }
00105 
00113       public static DataTable GetDataFromFile(string fileName, int activeSheetIndex)
00114       {
00115          return Excel.GetDataFromFile(fileName, false, activeSheetIndex);
00116       }
00117 
00126       public static DataTable GetDataFromFile(string fileName, bool isCSV, int activeSheetIndex)
00127       {
00128          DataTable Data = null;
00129          if (isCSV) {
00130             Data = new DataTable("CSV");
00131             System.IO.FileStream FStream = null;
00132             try {
00133                FStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
00134             } catch (Exception ex) {
00135                string ErrorString = "There was an error trying to open the selected file. This can " +
00136                   "happen when the selected file is already open, please ensure the file is not opened " +
00137                   "in any other applications (like Excel)" + Environment.NewLine + "Error: " + ex.Message;
00138                Sylloge.App.Out(ErrorString);
00139                return null;
00140             }
00141             System.IO.StreamReader Reader = new System.IO.StreamReader(FStream);
00142             string[] Headers = Reader.ReadLine().Split(',');
00143             foreach (string Header in Headers) {
00144                Data.Columns.Add(Header);
00145                Application.DoEvents();
00146             }
00147             string[] Values = null;
00148             while (!Reader.EndOfStream) {
00149                Values = Reader.ReadLine().Split(',');
00150                if (Values.Length > Data.Columns.Count) {
00151                   for (int i = Data.Columns.Count; i < Values.Length; i++) {
00152                      Data.Columns.Add(new DataColumn(("column" + i.ToString("00"))));
00153                      Application.DoEvents();
00154                   }
00155                }
00156                Data.Rows.Add(Values);
00157                Application.DoEvents();
00158             }
00159             Reader.Close();
00160             FStream.Close();
00161          } else {
00162             if (Excel.Open(fileName)) {
00163                DataTable[] NewData = Excel.GetAll();
00164                Excel.Close(); // Once we have the data, we don't need the Excel object any more
00165                Data = NewData[activeSheetIndex]; // Index of 0 says first sheet
00166                string TableName = (new System.IO.FileInfo(fileName)).Name;
00167                Data.TableName = TableName.Substring(0, TableName.LastIndexOf('.'));
00168             } else {
00169                Sylloge.App.Out("There was an error trying to get the data from the file.");
00170             }
00171          }
00172          return Data;
00173       }
00174           
00178       public static string Name { get; set; }
00179 
00184       private static bool False()
00185       {
00186          Table.Clear();
00187          Dataset.Clear();
00188          return false;
00189       }
00190 
00195       public static bool Open()
00196       {
00197          return Excel.Open(Excel.Name, true);
00198       }
00199           
00205       public static bool Open(string fileName)
00206       {
00207          return Excel.Open(fileName, true);
00208       }
00209 
00216       public static bool Open(string fileName, bool hasHeaders)
00217       {
00218          Excel.Close();
00219          Excel.CreateNewInstances();
00220          Excel.Name = fileName;
00221          try {
00222             string Ver = "8.0";
00223             string Provider = "Microsoft.Jet.OLEDB.4.0";
00224             if ((new System.IO.FileInfo(fileName)).Extension.ToLower() == ".xlsx") {
00225                Provider = "Microsoft.ACE.OLEDB.12.0";
00226                Ver = "12.0 Xml"; 
00227             }
00228             Excel.Conn.ConnectionString = "Provider=" + Provider + ";Data Source=" + fileName + ";Extended Properties=\"Excel " + Ver + ";HDR=" + (hasHeaders ? "YES" : "NO") + ";\""; // Excel 8 = 97-03 (for backward compatibilty)
00229             Excel.Conn.Open();
00230             Excel.Adapter.DeleteCommand.Connection = Conn;
00231             Excel.Adapter.InsertCommand.Connection = Conn;
00232             Excel.Adapter.SelectCommand.Connection = Conn;
00233             Excel.Adapter.UpdateCommand.Connection = Conn;
00234             Excel.IsOpen = true;
00235          } catch (Exception ex) {
00236             // Reason for this could be invalid password
00237             Sylloge.App.Out("There was an error while trying to open the Excel file.", ex);
00238             Excel.IsOpen = false;
00239             return false;
00240          }
00241          return Excel.IsOpen;
00242       }
00243 
00248       public static long Size()
00249       {
00250          long Value = 0;
00251          try {
00252             if (System.IO.File.Exists(Excel.Name)) {
00253                Value = new System.IO.FileInfo(Excel.Name).Length;
00254             }
00255          } catch (Exception ex) {
00256             Console.WriteLine(ex.Message);
00257          }
00258          return Value;
00259       }
00260 
00261       #endregion
00262 
00263       #region Importing
00264 
00269       public static DataTable[] GetAll()
00270       {
00271          DataTable Tables = Excel.Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
00272          if (Tables == null) { return null; }
00273          List<string> Sheets = new List<string>();
00274          foreach (DataRow Row in Tables.Rows) {
00275             Sheets.Add(Row["TABLE_NAME"].ToString());
00276          }
00277          List<DataTable> TableList = new List<DataTable>();
00278          foreach (string Table in Sheets) {
00279             DataTable NextTable = Excel.Query("SELECT * FROM [" + Table + "]", Table);
00280             if (NextTable == null || NextTable.Columns.Count == 0 || NextTable.Rows.Count == 0) { continue; }
00281             DataTable Tmp = new DataTable(NextTable.TableName);
00282             foreach (DataColumn Column in NextTable.Columns) {
00283                Tmp.Columns.Add(Column.ColumnName);
00284             }
00285             foreach (DataRow Row in NextTable.Rows) {
00286                Tmp.ImportRow(Row);
00287             }
00288             TableList.Add(Tmp);
00289          }
00290          return TableList.ToArray();
00291       }
00292 
00293       public static string[] GetTableNames()
00294       {
00295          DataTable Tables = Excel.Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
00296          if (Tables == null) { return null; }
00297          List<string> Sheets = new List<string>();
00298          foreach (DataRow Row in Tables.Rows) {
00299             Sheets.Add(Row["TABLE_NAME"].ToString());
00300          }
00301          return Sheets.ToArray();
00302       }
00303 
00308       public static string GetReleventTable()
00309       {
00310          DataTable Tables = Excel.Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
00311          if (Tables == null) { return null; }
00312          foreach (DataRow Row in Tables.Rows) {
00313             if (!Row["TABLE_NAME"].ToString().ToLower().Contains("sheet")) {
00314                return "[" + Row["TABLE_NAME"].ToString() + "]";
00315             }
00316          }
00317          return "[Sheet1$]";
00318       }
00319 
00325       public static DataTable Query(string query)
00326       {
00327          try {
00328             string table = Excel.GetReleventTable();
00329             Excel.Dataset.Clear();
00330             Excel.Adapter.SelectCommand.CommandText = query;
00331             Excel.Adapter.SelectCommand.ExecuteNonQuery();
00332             Excel.Adapter.Fill(Excel.Dataset, table);
00333             return Dataset.Tables[table];
00334          } catch (System.Data.OleDb.OleDbException oleEx) {
00335             // If this happens, it could be a number of reasons, but typically its becuase
00336             // the OLE adapter could not find a piece of data (like a Sheet or table)
00337             Sylloge.App.Out(oleEx.Message);
00338          } catch (Exception ex) {
00339             Sylloge.App.Out("There was a programming error trying to access the Excel data." + Environment.NewLine + ex.Message);
00340          }
00341          return null;
00342       }
00343           
00350       public static DataTable Query(string query, string table)
00351       {
00352          try {
00353             Excel.Dataset.Clear();
00354             Excel.Adapter.SelectCommand.CommandText = query;
00355             Excel.Adapter.SelectCommand.ExecuteNonQuery();
00356             Excel.Adapter.Fill(Excel.Dataset, table);
00357             return Dataset.Tables[table];
00358          } catch (System.Data.OleDb.OleDbException oleEx) {
00359             // If this happens, it could be a number of reasons, but typically its becuase
00360             // the OLE adapter could not find a piece of data (like a Sheet or table)
00361             Sylloge.App.Out(oleEx.Message);
00362          } catch (Exception ex) {
00363             Sylloge.App.Out("There was a programming error trying to access the Excel data.", ex);
00364          }
00365          return null;
00366       }
00367 
00368       #endregion
00369 
00370       #region Exporting
00371 
00378       public static bool CreateTable(string tableName, string[] columns)
00379       {
00380          string Create = "CREATE TABLE " + tableName + " (";
00381          for (int FieldCount = 0; FieldCount < columns.Length; FieldCount++) {
00382             Create += "[" + columns[FieldCount] + "] char(255)";
00383             if (FieldCount < columns.Length - 1) { Create += ", "; }
00384          }
00385          Create += ")";
00386          try {
00387             Excel.Dataset.Clear();
00388             Excel.Adapter.InsertCommand.CommandText = Create;
00389             Excel.Adapter.InsertCommand.ExecuteNonQuery();
00390          } catch (Exception ex) {
00391             Sylloge.App.Out("There was an error exporting the data: " + ex.Message);
00392             return false;
00393          }
00394          return true;
00395       }
00396 
00404       public static bool AddItem(string tableName, string[] columns, object item)
00405       {
00406          // TODO: Change the 'object' item to whatever you want to add and update this section of code
00407          try {
00408             string ItemValue = string.Empty;
00409             string Query = "INSERT INTO [" + tableName + "$] (";
00410             for (int Index = 0; Index < columns.Length; Index++) {
00411                Query += "[" + columns[Index] + "]";
00412                if (Index < columns.Length - 1) { Query += ","; }
00413             }
00414             if (Query.Substring(Query.Length - 1, 1) == ",") { Query = Query.Substring(0, Query.Length - 1); }
00415             Query += ") VALUES (";
00416             Query += "'" + ((int)item).ToString() + "',";
00417             Query += "'" + ((string)item) + "'";
00418             Query += ")";
00419             Excel.Dataset.Clear();
00420             Excel.Adapter.InsertCommand.CommandText = Query;
00421             Excel.Adapter.InsertCommand.ExecuteNonQuery();
00422          } catch (Exception ex) {
00423             Sylloge.App.Out("There was an error trying to add the item" + ex.Message);
00424             return false;
00425          }
00426          return true;
00427       }
00428 
00429       #endregion
00430    }
00431 }
 All Classes Namespaces Files Functions Variables Enumerations Properties Events