nyk0r

Reading .xls and .xlsx Files

May 3rd, 2012
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. // OELDB connection strings
  2. // http://www.arboundy.com/2010/11/the-microsoft.ace.oledb.12.0-provider-is-not-registered-on-the-local-machine/
  3. // http://www.microsoft.com/en-us/download/details.aspx?id=13255
  4. private const string EXCEL_2003_CONNECTION_STRING =
  5.     "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
  6. private const string EXCEL_2007_CONNECTION_STRING =
  7.     "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
  8. private const string SELECT_STATEMENT = "SELECT * FROM [{0}]";
  9.  
  10. private static OleDbConnection Connect(string file)
  11. {
  12.     OleDbConnection result = null;
  13.     try
  14.     {
  15.         result = new OleDbConnection(String.Format(EXCEL_2003_CONNECTION_STRING, file));
  16.         result.Open();
  17.     }
  18.     catch
  19.     {
  20.         result = new OleDbConnection(String.Format(EXCEL_2007_CONNECTION_STRING, file));
  21.         result.Open();
  22.     }
  23.     return result;
  24. }
  25.  
  26. // http://stackoverflow.com/questions/1164698/using-excel-oledb-to-get-sheet-names-in-sheet-order
  27. private static String[] GetExcelSheetNames(OleDbConnection conn)
  28. {
  29.     using (var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
  30.     {
  31.         if (dt == null) return null;
  32.         return dt.Rows.OfType<DataRow>().Select(row => row["TABLE_NAME"].ToString()).ToArray();
  33.     }
  34. }
  35.  
  36. private static DataTable GetTableFromFirstExcelSheet(string path)
  37. {
  38.     using (var conn = Connect(path))
  39.     {
  40.         var sheetName = GetExcelSheetNames(conn)[0];
  41.         using (var comm = conn.CreateCommand())
  42.         {
  43.             comm.CommandText = String.Format(SELECT_STATEMENT, sheetName);
  44.  
  45.             using (var adapter = new OleDbDataAdapter())
  46.             {
  47.                 adapter.SelectCommand = comm;
  48.  
  49.                 DataTable table = new DataTable();
  50.                 adapter.Fill(table);
  51.                 return table;
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment