I am looking to read data from excel 2010
by specifying the sheet name. Then I want to convert the data into JSON format. Assume I have an excel sheet like this.
Name | Age | Country
Waugh, Timothy 10 UK
Freeman, Neil 20 USA
Andy, Robert 30 Poland
Should results in:
[{"Name":"Waugh, Timothy","Age":10.0,"Country":"UK"},
{"Name":"Freeman, Neil","Age":20.0,"Country":"USA"},
{"Name":"Andy, Robert","Age":30.0,"Country":"Poland"}]
So far I am using this code:
var pathToExcel = @"C:\temp\file.xlsx";
var sheetName = "sheetOne";
//This connection string works if you have Office 2007+ installed and your
//data is saved in a .xlsx file
var connectionString = String.Format(@"
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={0};
Extended Properties=""Excel 12.0 Xml;HDR=YES""
", pathToExcel);
//Creating and opening a data connection to the Excel sheet
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = String.Format(
@"SELECT * FROM [{0}$]",
sheetName
);
using (var rdr = cmd.ExecuteReader())
{
//LINQ query - when executed will create anonymous objects for each row
var query =
from DbDataRecord row in rdr
select new
{
Name = row[0],
Age = row[1],
Country = row[2]
};
//Generates JSON from the LINQ query
var json = JsonConvert.SerializeObject(query);
return json;
}
}
Issues:
- I have to hard code the columns name. Column names are not dynamic.
- With this code, i am not able to read the first row (which should ideally serve as the column name)