How to append values to an Excel file? - c#

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.

Related

When I try read Excel with OLE DB all values are empty

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.

How to read data from excel file using c# [duplicate]

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.

Shall I read an excel file via OleDb Jet4.0 and save into dataset?

I have to read an excel file and put into a dataset.
Shall I read excel file content via OleDbDataAdapter, and then Fill into a dataset?
I tried but faild. It said the application cannot recognize database format when data adapter is doing Fill method.
Code:
String queryAll = "SELECT * FROM [Sheet1$]";
String xlsPath = Directory.GetCurrentDirectory() + "\\paid.xls";
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsPath;
try
{
m_dbDA = new OleDbDataAdapter(queryAll, strConn);
DataSet dsPaidXls = new DataSet();
m_dbDA.Fill(dsPaidXls); //exception here
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
Does it mean there is no way to directly read an excel data and put into a new dataset?
And the only one way is to read excel data cell by cell and insert to a new DataSet with datatable?
Thanks in advance.
========================================
Resolved
========================================
String queryAll = "SELECT * FROM [Sheet1$]";
String xlsPath = Directory.GetCurrentDirectory() + "\\paid.xls";
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsPath +
";Extended Properties='Excel 8.0;IMEX=1';";
try
{
m_dbDA = new OleDbDataAdapter(queryAll, strConn);
DataSet dsPaidXls = new DataSet();
m_dbDA.Fill(dsPaidXls,"[Sheet1$]");
dataGridView1.DataSource = dsPaidXls;
dataGridView1.DataMember = "[Sheet1$]";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
OLEDB works quite well once you have the correct connection string and are aware of issues with data types. Jet is for versions prior to 2007 and you need to add extended properties for Excel.
String strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ xlsPath + "Extended Properties='Excel 12.0 Xml;HDR=YES';";
See:
Connection Strings
How To Use ADO with Excel Data from Visual Basic or VBA (contains useful notes)
Various notes
When you read Excel files via OleDB, make sure you have the right version of the provider (one for xls, one for xlsx), and also make sure you have x86 selected as platform.
If you don't, it will compile to x64 on a 64-Bit system, and because OleDb is deprecated, there are no 64-bit OleDb drivers, which means your program will crash on calling OleDb.
Also, the Office 2007 system driver (ACE Data Connectivity Components) must be installed.
See here:
Diagnosing an OLEDB exception when Quering Excel 2010
You could also use ODBC or Excel Package Plus.
Again, you need to take a different libary here if the format is xls and not xlsx.
ExcelLibrary for XLS
http://code.google.com/p/excellibrary/
Excel Package Plus for XLSX
http://epplus.codeplex.com/
You should avoid using OleDb to read Excel files. Many pitfals.
For xls files, this works much better and more reliably.
http://www.codeproject.com/KB/office/ExcelReader.aspx
For xlsx files, use the Office Open XML SDK:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=5124

C# read open Excel file through OleDb

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 ());

C# 3.5 Reading Excel files

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.

Categories