Read Data from Excel using OLEDB - c#

I read an excel file using OLEDB. Below is the code:
string conn;
conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
("Data Source=" + _filename + ";" +
"Extended Properties=\"Excel 12.0;\""));
OleDbConnection oleDBCon = new OleDbConnection(conn);
oleDBCon.Open();
DataTable dt = oleDBCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SSQL = "SELECT * from [ Sheet1$ ]";
OleDbDataAdapter oleDA = new OleDbDataAdapter(SSQL, conn);
DataSet ds = new DataSet();
oleDA.Fill(ds);
DataTable _DtTable = ds.Tables[0];
oleDBCon.Close();
dataGridView1.DataSource = _DtTable;
foreach (DataRow rows in _DtTable.Rows)
{
string Description = rows[0].ToString();
string Code= rows[1].ToString();
textBox1.AppendText("Printing Description: " + Description + " and Code: " + Code + ",Date:" + DateTime.Now.ToString() + Environment.NewLine);
}
The excel file is as follows:
The data printed in textBox1 are:
Printing Description:Desc 2 and Code: Code 2,Date:20/12/2014 12:36:54 μμ
Printing Description: Desc 3 and Code: Code 3,Date:20/12/2014 12:36:54 μμ
So, my problem is that the 1st row of excel is going to the header of the Datatable. How can I avoid that (without adding any extra 1st row to excel)?

Just add "HDR=No" at the end of your connection string which means "No header row that indicates column but it contains data", then you will be able to fetch 1st row data also.
So your complete connection string would be
conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
("Data Source=" + _filename + ";" +
"Extended Properties=\"Excel 12.0;\";HDR=No"));

Related

C# - OleDBDataAdapter.Fill(DataSet) throws "No value given for one or more required parameters. "

I have the following code to access a .xlsx file and get the sheet named "Sheet1" as a table. Then I select the values for URL and Username using select command.
string strPath = #"C:\Users\...\TestData.xlsx";
string strExcelConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";");
OleDbConnection connExcel = new OleDbConnection(strExcelConn);
try
{
connExcel.Open();
DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmdExcel = new OleDbCommand("SELECT URL, Username From [" + SheetName + "]",connExcel);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT URL, Username From [" + SheetName + "]", strExcelConn);
cmdExcel.CommandText = "SELECT URL, Username From [" + SheetName + "]";
Console.WriteLine(cmdExcel.CommandText);
da.Fill(ds);
connExcel.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
connExcel.Close();
}
Unfortunately, I'm getting the following error during the datafill of the adapter.
da.Fill(ds);
The error says
Message: System.Data.OleDb.OleDbException : No value given for one or more required parameters.
Could someone help me find a solution for this?
The problem was only when I tried to select specific columns. If I have Select * from, it works fine.
But, not sure about the actual issue though.

How to load multiple sheet of excel(2016) file in ssis

This code perfectly work on my machine (I have excel 2010) but when my supervisor tried to run but not work on his machine(he have excel 2016) so for excel 2016 do i need to change connection
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";??
string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
string TableName = Dts.Variables["User::TableName"].Value.ToString();
string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
string SheetNameToLoad = Dts.Variables["User::SheetNameLike"].Value.ToString();
var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();
//Declare and initilize variables
string fileFullPath = "";
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["DBconnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
////Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "\\" + file.Name;
MessageBox.Show(fileFullPath);
// //Create Excel Connection
string ConStr;
string HDR;
HDR = "YES";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);
// //Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
//Only read data from provided SheetNumber
foreach (DataRow drSheet in dtSheet.Rows)
{
sheetname = drSheet["TABLE_NAME"].ToString();
MessageBox.Show(sheetname);
//Load the Data if Sheet Name contains value of SheetNameLike
if (sheetname.Contains(SheetNameToLoad) == true)
{
//Load the DataTable with Sheet Data so we can get the column header
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "] where CityName ='ARLINGTON'", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(myADONETConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
BC.WriteToServer(dt);
}
}
}
Did he get the error says ACE provider is not registered? If so, your supervisor need to download and install this on his machine:
https://www.microsoft.com/en-us/download/details.aspx?id=13255

Reading an Excel file into a DataTable includes system-defined columns

I am writing a program to read excel using c# and store in a DataTable. When I check the columns in my DataTable while debugging, I see system columns like Table_Schema, Table_Catalog, Table_Name, Table_Type etc. How do I exclude these unwanted columns?
My code:
string sSheetName = null;
string sConnection = null;
int nOutputRow = 0;
DataTable dtTablesList = default(DataTable);
OleDbCommand oleExcelCommand = default(OleDbCommand);
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFileName.Text + ";" + "Extended Properties=Excel 8.0;";
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0].Field<string>("TABLE_NAME");
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName))
{
oleExcelCommand = oleExcelConnection.CreateCommand();
string commandText = "Select * From [" + sSheetName + "]";
oleExcelCommand.CommandType = CommandType.Text;
OleDbDataAdapter daexcel = new OleDbDataAdapter(commandText, oleExcelConnection);
dtTablesList.Locale = System.Globalization.CultureInfo.CurrentCulture;
daexcel.Fill(dtTablesList);
}
oleExcelConnection.Close();

Copy excel table into DataTable faster

I am trying to copy an excel sheet with 1 Million records into a Data Table. Unfortunately it takes about 47 seconds to complete this process. Is there a better way to copy this information over in less time?
Here's the code that ports the info in:
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileName +
";Extended Properties='Excel 12.0 XML;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + sheetName + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
dtTemp.Reset();
dtTemp.TableName = userUpload;
sda.Fill(dtTemp); //Puts imported table into the dtTemp table
con.Close();
string fields = "";
string tempString;
foreach (DataColumn col in dtTemp.Columns) //Generates SQL String from imported table
{
tempString = RemoveSpecialCharacters(col.ColumnName);
if (dtTemp.Columns.IndexOf(col) == dtTemp.Columns.Count - 1)
{
fields += " [" + tempString + "] varchar(255)";
}
else
{
fields += " [" + tempString + "] varchar(255)" + ",";
}
}
fields = fields.Trim();
// createSQLConn(fields, connection, connectionTempDB, dtTemp);
}

C# Failing To Import All of the Cells from an Excel Spreadsheet

I am using some legacy code to return an Excel worksheet as a Dataset. However, when I iterate over the resulting data set it seems that not all of the cells are there. The Excel sheet that is being read has some merged cells and I am wondering if that is the problem. Here is the code:
private DataSet Get_Spreadsheet_Data(string strFileName, string strSheetName)
{
DataSet ds = new DataSet();
string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(strConnectionString);
try
{
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + strSheetName + "$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(ds);
}
catch (Exception Ex)
{
//litOutput.Text = "<span style=\"color:red;\">Exception Occurred pulling data from the spreadsheet.</span><br>Details: " + Ex.Message;
}
finally
{
objConn.Close();
objConn.Dispose();
}
return ds;
}
Is this code malfunctioning? Any advice is appreciated.
string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties=Excel 8.0;";
needed to read:
string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties="Excel 8.0;HDR=NO;IMEX=1;";
and that did the trick!
Have you tried running the same code with an Excel file that doesn't have the merged files?
That is the first thing I would try if I would wonder if merged cells can cause problems filling your dataset...
Edit for clarification:
For debugging purposes: use the same Excel file, only make sure you undo the merging of the cells.
Even better is to start with an excel file with 3 rows and 3 columns:
Row one: Cell A1 with value 'Foo; Cell B1 'Bar', C1 banana.
Row two: Cell A2 Foo1 B2 Bar1 <-- merge those two cells. C2 = Apple.
Row three: Cell A3 with value 'Foo2; Cell B3 'Bar2' C3 Orange <-- to check if the next line is read well after using merged cells...

Categories

Resources