Wednesday, April 9, 2014

How to read data from excel (*.xlsx) file using Microsoft.ACE.OLEDB.12.0

In our last post, we have seen how to get column header list from Excel using Open XML SDK 2.5. You can refer below link.

Now, we will see how to read data from excel file Product.xlsx which is shown below and convert it to XML format to send to database.

C#.NET Code
protected void ReadExcel()
string path = Server.MapPath("Product.xlsx");

System.Data.OleDb.OleDbConnection oledbConn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");

System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandTimeout = 0;
cmd.Connection = oledbConn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";

System.Data.OleDb.OleDbDataAdapter oleda = new System.Data.OleDb.OleDbDataAdapter();
oleda = new System.Data.OleDb.OleDbDataAdapter(cmd);

System.Data.DataSet ds;
ds = new System.Data.DataSet("ProductList");
oleda.Fill(ds, "Product");

XElement xeProductList = XElement.Parse(ds.GetXml());

catch (Exception ex)
throw ex;

Output XML
<Name>Asif Ghanchi</Name>
<Name>Ghanchi Asif</Name>
<Department>Production Support</Department>

You can also download sample excel from below location.

No comments:

Post a Comment