I have an excel file that contains some methods written in VB I think. I want to know any way makes me use these methods in C# code. I tried to make a connection with the file using (System.Data.Odbc.OdbcConnection), and then use the UPDATE statement by using Command, to enter the new data but the problem is that the cell which contains the function doesn't change it needs to open the excel file and save the new data to make the data updated.
// Get the path of the Excel file used to calculate the steam properties
string excelPath = System.Windows.Forms.Application.StartupPath + @"\SteamProp";
using (System.Data.OleDb.OleDbConnection MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+excelPath+"';Extended Properties=Excel 8.0;"))
{
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
MyConnection.Open();
myCommand.Connection = MyConnection;
string sql = "Update [test$] set temp = " + Temperature + ", press= " + Pressure + " where id=1";
myCommand.CommandType = System.Data.CommandType.Text;
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
}
I solved this problem using (Microsoft.Office.Interop.Excel) to open the file and save the new updated cell then close it.
object oMissing = System.Reflection.Missing.Value;
Excel._Application oExcel = new Excel.Application();
Excel.Workbooks oBooks = oExcel.Workbooks;
Excel._Workbook oBook = oBooks.Open(excelPath, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
oBook.Save();
oBook.Close(true, excelPath , oMissing);
oExcel.DisplayAlerts = true;
using (System.Data.OleDb.OleDbConnection MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelPath + "';Extended Properties=Excel 8.0;"))
{
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
MyConnection.Open();
myCommand.Connection = MyConnection;
string sql = "select * from [test$]";
myCommand.CommandType = System.Data.CommandType.Text;
myCommand.CommandText = sql;
System.Data.OleDb.OleDbDataReader myDReader = myCommand.ExecuteReader();
myDReader.Read();
steamProperties[0] = Convert.ToDecimal(myDReader[6]);
steamProperties[1] = Convert.ToDecimal(myDReader[7]);
steamProperties[2] = Convert.ToDecimal(myDReader[8]);
}
return steamProperties;
It works but in my program i will update the cell in excel file more than 100 times and this will take so much time.
Does any one has solution for my problem?
The complete code of my project is here
Thanks.