Coder Perfect

Using C# to read Excel files

Problem

Is there a free or open source package that allows a C# program to read Excel files (.xls) directly?

It doesn’t have to be complicated; simply choose a worksheet and read the data as strings. I’ve been parsing the resulting (tab-delimited) file using Excel’s Export to Unicode text feature, but I’d prefer to eliminate the manual step.

Asked by dbkk

Solution #1

var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

This is the method I generally employ. It’s a little unusual because I generally use an AsEnumerable() at the table edit:

var data = ds.Tables["anyNameHere"].AsEnumerable();

Because of this, I can use LINQ to search and construct structs from the fields.

var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
                new MyContact
                    {
                        firstName= x.Field<string>("First Name"),
                        lastName = x.Field<string>("Last Name"),
                        phoneNumber =x.Field<string>("Phone Number"),
                    });

Answered by Robin Robinson

Solution #2

If the Excel file contains only simple data, you can read it using ADO.NET. The following are the connection strings:

http://www.connectionstrings.com/?carrier=excel2007 or http://www.connectionstrings.com/?carrier=excel

-Ryan

Update: After that, you may just select * from [Sheet1$] to read the spreadsheet.

Answered by 2 revs

Solution #3

Although the ADO.NET technique is quick and simple, it does have a few idiosyncrasies that you should be aware of, particularly in terms of how DataTypes are handled.

This wonderful post will assist you in avoiding the following typical blunders: http://blog.lab49.com/archives/196

Answered by Ian Nelson

Solution #4

For Excel 2003, I used the following:

Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";

StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
    sb.Append(prop.Key);
    sb.Append('=');
    sb.Append(prop.Value);
    sb.Append(';');
}
string properties = sb.ToString();

using (OleDbConnection conn = new OleDbConnection(properties))
{
    conn.Open();
    DataSet ds = new DataSet();
    string columns = String.Join(",", columnNames.ToArray());
    using (OleDbDataAdapter da = new OleDbDataAdapter(
        "SELECT " + columns + " FROM [" + worksheet + "$]", conn))
    {
        DataTable dt = new DataTable(tableName);
        da.Fill(dt);
        ds.Tables.Add(dt);
    }
}

Answered by Dmitry Shechtman

Solution #5

Excel Data Reader is a good option.

http://exceldatareader.codeplex.com/

In a production setting, I’ve used it to import enormous volumes of data from a variety of Excel files into SQL Server Compact. It performs admirably and is quite durable.

Answered by Michał Pawłowski

Post is based on https://stackoverflow.com/questions/15828/reading-excel-files-from-c-sharp