My Technical Notes

Tuesday, 19 February 2013

Reading an Excel Spreadsheet into a DataTable

The following is the code. Add a reference to Excel.dll from ExcelDataReader.

// using statements
using Excel;
using System.Data;

// code
DataTable dataTable;
string spreadsheetPath = testSpreadsheetPath;
using (System.IO.Stream s = new System.IO.FileStream(spreadsheetPath, System.IO.FileMode.Open))
    IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(s);
    excelReader.IsFirstRowAsColumnNames = true;
    var ds = excelReader.AsDataSet();
    dataTable = ds.Tables[0];

TODO Need to add a link to download my own compilation of ExcelDataReader.

No comments: