Read data from Excel - c#

I have been trying to read data from an excel file. It has been successful, but I enountered a problem. Whenever the format of the cell and the data entered in the cell is not matching then I get empty data
e.g
If the data cell is formatted as Date - dd/mm/yyyy, and the user enters 13/17/2011, the as the date format and the date entered is contradictory so the excel gives me entirely empty cell. Only if the cell format is text I get the data as entered.
Why is the excel file giving me empty cell in case the entered date format is not complying with the cell format set?
This is the code that reads the excel data
if(fileEXT.Equals(".xls"))
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=Excel 8.0");
}
else if(fileEXT.Equals(".xlsx"))
{
oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=\"Excel 12.0;HDR=YES;\"");
}
else if(fileEXT.Equals(".xlsm"))
{
oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=Excel 12.0 Macro");
}
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds,"LocationDetails");

You can change your connection string to
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=Excel 8.0;HDR=Yes;IMEX=1"
HDR=Yes;IMEX=1
tells OldDb driver that data at columns in defferent format.

Instead of OLEDB, I would suggest using EPPLus library to handle your excel files.It is very easy and comprehensive. Nuget package is also available for the same. http://nuget.org/packages/EPPlus

Related

C# OleDbDataAdapter. Date format when reading Excel file

I have connection string with IMEX option (all types are converted to string):
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"{0}\";Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\";", strFile);
I use followed code to read xslx file into DataTable
DataTable table = new DataTable(name);
string sql = "SELECT * FROM [" + name + "]";
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(table);
Program reads the same file on two computers.
When the program runs on the first computer, I get date like string "31.03.2021". When the program runs on the second computer, I get the date like string "3/31/2021".
I cannot get the same date format on both computers. I already tried to:
Change the language format in Windows settings.
Set
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Set
table.Locale = new CultureInfo("en-US");
Nothing helps
I couldn't find any Solution. So I started to use a option IMEX=0 instead of IMEX=1.
Date are read correctly as DateTime type.

C# Issue while importing Excel sheets

I've searched the internet for this and couldn't really find a question like it.I am coding an application that takes data from Excel and view it.
All of my tests were correct, but suddenly I found that Importing a column that contains set of numbers in a row then letters will result in not showing the fields that contain those letters at all
PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
System.Data.DataTable dtSchema = new System.Data.DataTable();
conn.Open();
dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string Sheet1 = dtSchema.Rows[0].Field<string>("TABLE_NAME");
conn.Close();
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + Sheet1 + "]", conn);
DataSet ds = new DataSet();
myDataAdapter.Fill(ds);
the first dataset is the regular result
7841
7847s
2344
2262
7738
JD32916
JD329161
JD318161
JD31716
JD7643
JD21116
7194
the second dataset is the problematic result (notice that I removed the 's' from "7847s")
7841
7847
2344
2262
7738
7194
as you can see, all the fields with letters in them just disappeared,
it only happens where there are 5 or more consecutive fields with no letters in them. example (2nd number from the top contains 's' to prevent that error from happening)
Use IMEX=1 in your extended properties to treat all columns as text values. Without it, the Jet provider will infer a data type based on whatever type the majority of the values in that column is, which may not be correct.
Secondly, since your data does not have a header row, you should use HDR=NO in your extended properties as well.

Search Excel sheet from ASP.NET C#

UPDATE:
I have found that this code works! it searches the Excel sheet and only outputs the data I need.
But can anyone explain to me why this works? how does it know that the first line in the spreadsheet is the "index"??
//Coneection String by default empty
string ConStr = "";
//connection string for that file which extantion is .xlsx
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\TestExcel.xlsx" + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
//making query
string query = "SELECT * FROM [lol$] where ID='i2200'";
//Providing connection
OleDbConnection conn = new OleDbConnection(ConStr);
//checking that connection state is closed or not if closed the
//open the connection
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//create command object
OleDbCommand cmd = new OleDbCommand(query, conn);
// create a data adapter and get the data into dataadapter
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the Excel data to data set
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
lblud.Text = "" + row["Hylde"];
}
OLD
I have been trying to do this for several hours now but no matter what i try, I don't end up with the result i want.
So now im "starting from scratch" again. See if I have approached this incorretly.
Question:
I wan't to create a ASPX website that can search my excel sheet for specific data.
Something like Select * from [Sheet1$] where Column A = i2200
then display only Column B and C from that specific row into a Label / two labels.
See picture here: http://itguruen.dk/EXCEL.png
Does anyone have a simple way of doing this?
Thanks in advance!
Jasper
Have you thought about importing the Excel Spreadsheet into a DataTable, and then analyse that DataTable to populate your labels? You can perform SQL queries on DataTables, so you'll be able to extract the exact data you require quite easily (the hardest part will be importing the Excel Spreadsheet into the DataTable).
There's a very detailed report on this process here: http://www.aspsnippets.com/Articles/Read-and-Import-Excel-File-into-DataSet-or-DataTable-using-C-and-VBNet-in-ASPNet.aspx
Update the post so you can see the solution.
Allthough I dont really know why this works??

Reading from excel file using oledb - empty strings

I'm using oledb to read from excel file.
DataTable sheet1 = new DataTable();
string excelCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
using (OleDbConnection connection = new OleDbConnection(excelCS))
{
connection.Open();
string selectSql = #"SELECT * FROM [Sheet1$]";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
adapter.Fill(sheet1);
}
connection.Close();
}
But there is a problem with some cells of the file.
For some cells I get an empty value instead of text. I tried to put some other text into these cells but it didn't work - I'm still getting empty strings.
But after deleting the column and inserting again my application get the right value of cell. Important is that the problem is not with all cells in the column.
Is this a problem with cell format or something? This excel file will be generated by another system so I won't be able to modify it manually.
Has anybody any sugestions what's wrong and what can I do?
Use IMEX = 1 at the end of your connection string. That will fix your problem.
To always use IMEX=1 is a safer way to retrieve data for mixed data
columns. .."
Remember that, sometimes there are some errors involved using IMEX while you're using Update rather than Selecting.
using this method convert Execel to Dataset without Empty String in c#
public static DataSet ConvertExcelToDataTable(string FileName)
{
DataSet ds = new DataSet();
string strConn = "";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FileName + ";Extended Properties=\"Excel 8.0; HDR=YES; IMEX=1;\"";
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);
da.Fill(ds);
return ds;
}
it will return dataset.
I had this issue. What I found was that on the cells that returned blank values the data looked like strings, but the rest of the data looked like numbers, so excel stored the strings in a different place as the numbers. I changed the column format to text and all the data was picked up.
This thread might help with changing the format: Format an Excel column (or cell) as Text in C#?

how do I read an xls file with datetime columns using OleDb

currently I am having sucsess with reading the excel file with my c# ,net 2 winform application. All works well with string and numerical types, but when it comes to date columns it still casts them as string.
I have read that ado.net scans the first eight rows and then uses that to determine the datatype...I have extended my test file to include more than eight rows - but I still have the same results.
thanks for any help you can provide
DataTable tbl = new DataTable();
OleDbConnection dbConnection =
new OleDbConnection (#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls;Extended Properties=""Excel 8.0;HDR=Yes;""");
dbConnection.Open();
try
{
OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", dbConnection);
dbAdapter.Fill(tbl);
}
finally
{
dbConnection.Close();
}
.net 2.0, c#, vs2008
Is the field formatted as date in the excel file?

Categories