Hello,
For a single cell I would use OleDb as shown below were cell address is a single cell rather than a range which can be done also.
SELECT * FROM [Sheet-name$cell-address:cell-address]
Let's read B10 from Sheet1
string value = "";
using (OleDbConnection cn = new OleDbConnection { ConnectionString = "TODO" })
{
cn.Open();
using (OleDbCommand cmd = new OleDbCommand
{
CommandText = "SELECT * FROM [Sheet1$B10:B10]",
Connection = cn
}
)
{
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
value = dr.GetString(0);
MessageBox.Show(value);
}
}
}
In regards to connection string, for simple connections the following function accepts a filename and parameter to indicate if the first row of the sheet to be read is data or column names, pass "Yes" for column names, "No" for data. Of course you can write the connection string yourself.
public string ConnectionString(string FileName, string Header)
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
if (System.IO.Path.GetExtension(FileName).ToUpper() == ".XLS")
{
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.Add("Extended Properties", string.Format("Excel 8.0;IMEX=1;HDR={0};", Header));
}
else
{
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.Add("Extended Properties", string.Format("Excel 12.0;IMEX=1;HDR={0};", Header));
}
Builder.DataSource = FileName;
return Builder.ConnectionString;
}
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.
No comments:
Post a Comment