I need to connect to an open Excel 2003 file using .NET 3.5
It seems the OleDb connection which I am trying to use wants the file exclusively. But I need to have this file open in Excel in the same time.
Is non-locking reading possible?
EDIT: I resolved this by copying file before opening it.
the question seems have no answer. and I cant delete it....
my solution was - run macro on timer to save the excel file in question and C# app was copying the file to another one and reading it using OleDb.
This seems like a similar problem:
Writing into excel file with OLEDB
Does that work out for you?
What parameters are you passing in when you open the Excel document? Could you set the "ReadOnly" parameter in Workbook.Open() to true? See here.
Refer to the code below how to get the information of Excel data into an array. Then you will perform any validations on that Excel sheet.
var fileName = #"D:\Pavan\WorkDiployed.xlsx";
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=Excel 12.0;", fileName);
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", con);
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
DataTable data = excelDataSet.Tables[0];
DataRow[] arrdata = data.Select();
foreach (DataRow rw in arrdata)
{
object[] cval = rw.ItemArray;
}
con.Close();
MessageBox.Show (excelDataSet.Tables[0].ToString ());
Related
I have done a little program to parser excel. It works fine only when before to execute it I open Excel file manually (is not it strange?). I.e. first I open excel file, second I execute program and I get good results
If I don't open excel before to execute it I get empty values
My connection string (excel file has extension .XLSX):
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + path + "\\" + f.Name + ";" +
"Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
My code to open connection with oleDB:
using (OleDbConnection cnn = new OleDbConnection(connectionString))
{
cnn.Open();
...
String sql = "SELECT * FROM [" + sheetNames[i] + "]";
OleDbDataAdapter da = new OleDbDataAdapter(sql, cnn);
DataTable dt = new DataTable();
da.Fill(dt); // Now 'dt' should has all data
}
Also, I have installed AccessDatabaseEngine.exe and AccessRuntime.exe
Obviously, my purpose is run the program without having to manually open the file. Any suggestion?
Thanks for your time.
I found it a real pain when I tried to get OleDb and Excel to play nicely together. Fortunately, I found a much better approach: EPPlus
EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
Open source, feature rich and easy to use. If at all possible, use it instead of OleDb.
This question already has answers here:
Reading Excel files from C#
(32 answers)
Closed 9 years ago.
My application needs to read data from an excel file. I am using .Net and c# for development.
I cannot install MS office in the system. Because of that the my application fails to read excel file and throws an error while loading the dll for excel.
How can i access excel file in my application in a system where ms office is not installed?
There is the option to use OleDB and use the Excel sheets like datatables in a database...
Just an example.....
string con =
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +
#"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
This example use the Microsoft.Jet.OleDb.4.0 provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.
The provider is called Microsoft.ACE.OLEDB.12.0;. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.
Of course you don't need Office installed on the target machine.
While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters
CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats
Good luck!
Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.
I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:
using System.Data;
using System.Data.OleDb;
namespace Data_Migration_Process_Creator
{
class Class1
{
private DataTable GetDataTable(string sql, string connectionString)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
private void GetExcel()
{
string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);
foreach (DataRow dr in dt.Rows)
{
//Do what you need to do with your data here
}
}
}
}
Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.
Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.
I know this question is very old but i am not finding any answer to this.
How to append values into existing excel file and to a particular column.
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=filelocation;Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into ["+ sheetname +"$] (Result) values ("+ result +")";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
I even tried different method like opening Excel through C# and append, nothing worked.
If you don't have to use OLEDB here is a good article how to operate excel files by using early binding.
You can checkout below links
http://www.aspsnippets.com/Articles/Export-Data-to-Excel-Sheet-using-ADO.Net-and-C.aspx
http://www.aspsnippets.com/Articles/Read-and-Import-Excel-Sheet-using-ADO.Net-and-C.aspx
Using OLEDB to work with excel files has it's problems and shortcomings. It is better to use a third-party library. I recomment CSharpJExcel for Excel 97-2003 (xls) files or EPPlus for Excel 2007 (xlsx) files. You don't need to even have Microsoft Excel installed.
I have a strange behavior when i try to read an XML worksheet using this code :
string CONNEC_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=No;IMEX=2;\"";
string fullFilePath = #"C:\Tmp\TestFile.xls";
using (OleDbConnection objCon = new OleDbConnection(string.Format(CONNEC_STRING, fullFilePath)))
{
using (OleDbCommand cm = new OleDbCommand("Select * From [MYCELLSRANGE]", objCon))
using (OleDbDataAdapter da = new OleDbDataAdapter(cm))
{
DataTable dt = new DataTable();
objCon.Open();
da.Fill(dt);
objCon.Close();
}
}
If the Excel file is closed, I receive the error 'External table is not in the expected format.'
When I open the file, if I execute the above code, it works fine and I can read data contained in MYCELLSRANGE.
So, has anyone any idea about this problem ?
Thanks for answers.
I believe its because the Jet Engine uses the Excel app to interpret the file. I ran into this issue once myself. When you use the Excel.dll reference and you interpret the Excel file from that you have to create a new Application instance to read the file. Jet just does this very thing to get the data. I suggest using that code instead.
C# Corner example of how to Import Excel to a ListView
C# Corner example of how to Create an Excel Worksheet in C#
MSDN users discussing the same topic
If you would like further assistance, let me know. I have successfully done this in VB.NET in various applications of mine.
I have to automate something for the finance dpt. I've got an Excel file which I want to read using OleDb:
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=A_File.xls;Extended Properties=""HTML Import;IMEX=1;""";
using (OleDbConnection connection = new OleDbConnection())
{
using (DbCommand command = connection.CreateCommand())
{
connection.ConnectionString = connectionString;
connection.Open();
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
{
//raise exception if needed
}
command.CommandText = "SELECT * FROM [NameOfTheWorksheet$]";
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
//do something with the data
}
}
}
}
Normally the connectionstring would have an extended property "Excel 8.0", but the file can't be read that way because it seems to be an html file renamed to .xls.
when I copy the data from the xls to a new xls, I can read the new xls with the E.P. set to "Excel 8.0".
Yes, I can read the file by creating an instance of Excel, but I rather not..
Any idea how I can read the xls using OleDb without making manual changes to the xls or by playing with ranges in a instanciated Excel?
Regards,
Michel
I asked this same question on another forum and got the answer so I figured I'd share it here. As per this article: http://ewbi.blogs.com/develops/2006/12/reading_html_ta.html
Instead of using the sheetname, you must use the page title in the select statement without the $. SELECT * FROM [HTMLPageTitle]
I've been searching so many solution, end up I found something really simple and easy -
to import XML file to Excel file, I tried to convert XML to HTML first, use -
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
then I found I could easily change my output file as .xls, instead of .html
//create the output stream
XmlTextWriter myWriter = new XmlTextWriter
("result.html", null);
then the output is perfect Excel file from my XML data file.
hope this will save ur work.
I have run into the same problem. As previously mentioned, it seems to be an html file renamed to .xls. When I copy the data from the xls to a new xls, I can read the new xls with the E.P. set to "Excel 8.0".
In this scenario, the file couldn't be saved in the correct format. So we have to convert that file to the correct format. To do this, use MS Office Excel 2007, Click File -> Convert. The file will be converted to the right format automatically.