Skip to content

Instantly share code, notes, and snippets.

@johnweldon
Created October 9, 2012 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnweldon/3861291 to your computer and use it in GitHub Desktop.
Save johnweldon/3861291 to your computer and use it in GitHub Desktop.
Read Excel .xlsx file and return first worksheet as a DataTable
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
namespace JW4.DB.Util
{
public static class Excel
{
public static DataTable GetFirstWorksheetAsTable(string filename)
{
var ds = new DataSet();
using (var conn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", filename)))
{
conn.Open();
var worksheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "Table"});
Debug.Assert(worksheets != null, "worksheets != null");
var firstsheet = worksheets.Rows[0][2].ToString();
var query = string.Format("SELECT * FROM [{0}]", firstsheet);
var adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);
}
var table = ds.Tables[0];
return table;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment