Created
October 9, 2012 20:44
-
-
Save johnweldon/3861291 to your computer and use it in GitHub Desktop.
Read Excel .xlsx file and return first worksheet as a DataTable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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