Reading Excel File using C# - c#

I am new to C# and I am trying to read an excel file with the following code
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath +
";Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(conStr))
{
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);
}
}
}
I get the following error:
Sheet1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
Can anyone tell me whats I am doing wrong?
The name of excel sheet is sheet.xlsx
Thanks

The sheet name might not be the same as the filename, you can get the first sheet name by doing the following
First, get the schema
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
Then get the first sheets name
var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
After you get your command, you can then fill a dataset and work with it's .Rows collection
var myDataSet = new DataSet();
command.Fill(myDataSet);
The sheetname is this

Related

Updating excel values in data grid view on certain condition

I need to fetch a row value from an excel sheet in data grid view in winform.
I’m able to display the entire excel sheet in the datagridview. But, I need to display particular rows in the grid based on a current date condition.
public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$] WHERE Date=#date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("#date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}
Thanking you in advance
What seems to be happening here is that the Date parameter is not being honored, as you are getting back all of the rows. So, I used Google to figure out how to properly add parameters when using OleDbConnection. I found this:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement
Source: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters
Using the example on that page, try changing your code to this:
string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$] WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
Please note that i've not tested this, so I can't promise it will work. But, the main point is... the answer is out there! You just need to go looking for it.

SQL Query against EXCEL Spreedsheet containing formulas

I am writing a component in C# which returns data from an EXCEl spreadsheet using Microsoft.ACE.OLEDB.12.0. The spreadsheet contains cells with formulas and references to other spreadsheets within that workbook. These cells return no data to the DataTable. See example below.
OleDbConnection OleDBconn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"",InputFile));
OleDbCommand OleCommand = new OleDbCommand();
OleCommand.Connection = OleDBconn;
OleDBconn.Open();
dtXLS = OleDBconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(OleCommand);
OleCommand.CommandText = string.Format(#"SELECT [Column] From [Sheet1$]");
adp.SelectCommand = OleCommand;
adp.Fill(dt);
Column contains cells with formulas and references to other worksheets in the workbook. So dt[0][Column] is null when it should have a value. The cell in the spreadsheet contains the below reference
=dd!B2
here is something that you can try in regards to filling and returning the DataTable
//call the method this way
var someDataTable = ExecuteDataSet("SELECT * FROM [Sheet1$]", InputFile);
public static DataTable ExecuteDataSet(string sql, string InputFile)
{
using (DataSet myDataset = new DataSet())
using (OleDbConnection OleDBconn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"",InputFile));
using (OleDbCommand cmdSelect = new OleDbCommand(sql, OleDBconn))
{
try
{
OleDBconn.Open();
dtXLS = OleDBconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//if you need to return this change the method signature to out param for this
new OleDbDataAdapter(cmdSelect).Fill(myDataset);
}
catch (Exception ex)
{
//Show a message or log a message on ex.Message
}
return myDataset.Tables[0];
}
}

in C# using oledb connection string how to Convert Scientific Notation to text strings?

I have a set of data that is downloaded as a Excel file using OLEDB connection string like so:
4552
3.00E+03
3.00E+22
3F45
3.00E+99
DD56677
37
Excel automatically thinks that 3E03, 3E22 and 3E99 are numbers and makes them look like above..
how to get it as a string ?
my code is
DataTable dataTable = new DataTable();
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=" + strFilePath + ";"
+ "Extended Properties='Excel 8.0;HDR=" + header + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text'";
OleDbConnection connection = new OleDbConnection(strExcelConn);
using (OleDbCommand command = new OleDbCommand())
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
command.Connection = connection;
//Check if the Sheet Exists
connection.Open();
DataTable dtExcelSchema;
//Get the Schema of the WorkBook
dtExcelSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connection.Close();
connection.Open();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
command.CommandText = "SELECT * From [" + SheetName + "]";
adapter.SelectCommand = command;
adapter.Fill(dataTable);
connection.Close();
}
please can any one help me to get this colum as a string
Have a look at this StackOverflow question entitled How to convert a string containing an exponential number to decimal and back to string.
They use the decimal.Parse(someMoneyVar, NumberStyles.Any) method to do the conversion.
Select Excel Columns by name in your query and cast your required columns to a string using CStr(<columnName>)

data import from excel facing an issue

I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>

asp.net mvc c# sqkbulkcopy No Value given for one or more required parameter

i am having this error No Value given for one or more required parameter
what might be the reason for the error. here is the code
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + postdir + newFileNameOnServer + "; Extended Properties=Excel 8.0";
using (OleDbConnection connection =new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select Month,Year,CountryofExport,CountryofOrigin,Hs_code,quantity,Unit,CustomValue,Type FROM [qryTradeFlowforWeb$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader()) // the error coming here
{
string sqlConnectionString = ConfigurationManager.ConnectionStrings["KMFConnectionString"].ToString();
SqlConnection conn = new SqlConnection(sqlConnectionString);
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelData";
bulkCopy.WriteToServer(dr);
}
}
}
Compare the destinatin table clolum list is identical with the source table column list. if not map the source and destination colum details using
bulkCopy.ColumnMappings.Add("SourceCol", "DestinationCol1");
bulkCopy.ColumnMappings.Add("SourceCo2", "DestinationCol2");
bulkCopy.ColumnMappings.Add("SourceCo3", "DestinationCol3");

Categories