I am new to c# and i have a simple project on c# in which i want to get some data from excel in c# and i want to save it in database, i have no idea about it, i found the following code and its working well but not giving me the data, here is code:
var fileName = @"C:\Users\AhsanWindows8\Desktop\Book1.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
}
}
now this is how my excel file looks like
Can I get this data in a dictionary like key value pair, suppose English word on left side will be key and text on right side will be value.
Try this:
cmd.CommandText =
"SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "$] ";
When dataset will be filled you can use this code to construct dictionary.
var dict = new Dictionary<string, string>();
foreach(DataRow row in ds.Tables[0].Rows)
{
dict.Add(row[0].ToString(), row[1].ToString());
}
If you are familiar with LINQ, you can try use this:
ds.Tables[0].Rows.ToDictionary(r => r[0].Tostring(), r => r[1].Tostring());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.