Query an Excel spreadsheet - c#

I have a project where I need to query an Excel spreadsheet. Basically I need to read a two column Excel spreadsheet into a dictionary table. I have a database of error codes and descriptions for each code. The project requires Excel (Excel 2007 compatible .xlsx) because the user wants to add new Key/Description pairs by editing an Excel spread sheet.
The idea is that I am going to get a list of error codes and I simply want to be able to display a table in a worksheet with error code and the associated description from the Excel spreadsheet, or no description found.
I figure if I can get the table (which is not very long) into a dictionary table the rest would straight forward but I cannot even find a starting point using the current version C# and 4.5.2 .NET API. I just need to open the worksheet and read the two column table into a dictionary table and I am off to the races.
Can someone please get me started in the right direction please?

You can probably use OleDbConnection to get the data from Excel.
OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source="
+ xlsx file with path
+ ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("SELECT * FROM [" + SHEETNAME_HERE + "$A1:B65]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
Once you have the data filled up, you can fetch the data in dictionary or any other object of List Enumerable.

Related

Can't read file after 8th row EXCEL OLE DB

I can't read this excel file of mine after the 8th row. I am using a OLEDB connection to access it from a c# script task inside a SSIS package :
strCoExcel = "Provider = Microsoft.ACE.OLEDB.12.0;Mode=Read;Data Source =" + Path.Combine((string)Dts.Variables["PathINPUT"].Value, Dts.Variables["FileNameForEach"].Value.ToString()) + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO;ImportMixedTypes=Text;TypeGuessRows=0;IMEX=1;\"";
//Gathering data from the renamed sheet
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [DataTQT$]", coExcel);
DataTable data = new DataTable();
adapter.Fill(data);
What is wrong:
Some excel files are opened and everything is fine but others do not produce any rows or only 8.
I tried the following:
-HDR no/yes
-IMEX =1 doesnt change anything
-nor do ImportMixedTypes=Text;TypeGuessRows=0
-setting all the cell from the excel file to standard or text field
any help ?
OK so the final answer for me was not in this piece of code as suspected by others.
This data goes into a SQL database and the columns were not big enough for the data i wanted to insert. I modified the table and now everything works fine.

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.

Inserting Specific Column of Data From Excel Sheet

I have a website where one of the functions is importing excel sheets to a SQL database. Right now I am loading the data into a data table and then assigning a variable to a column index. That is working just fine, but if the excel sheet is in a different format then it wont import to the database.
Does anyone know of another way to import a specific column(s) into a SQL database other than using the column index? I have also used the column name, but what if the column name changes?
You can use like this.
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "anyNameHere");
DataTable data = ds.Tables["anyNameHere"];
The references for this is
1) How to read data from excel file using c#
2) Reading Excel files from C#
I hope it helps.

Reading locked Excel (.xlsx) file, Using C#

Here is my code to read uploaded Excel file. Which is working absolutely fine for past 3 months.
var connectionString = GetOleDbConnectionString(file);
using (var dataAdapter = new OleDbDataAdapter("select * from [Sheet1$]", connectionString))
{
dataAdapter.Fill(ds, tableCount.ToString());
}
private static string GetOleDbConnectionString(string file)
{
var fileExtension = Path.GetExtension(file);
if (fileExtension.EqualsCCIC(".xlsx"))
{
return #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;".F(file);
}
}
Problem: Uploaded excel file got "StartDate" as first column. But this column also has employee name along with dates (I need to read this employee name to process this sheet).
I came across one new excel file (Excel2007 .xlsx). When I upload new file (Which has both employee name and dates) it is only reading dates from the column and ignoring employee names. my dataset showing (While debugging) those cells in data table as empty strings. According to business logic I need to know which employee these dates belongs to. I removed locks for entire sheet(cell formatting>>Protection>> lock) but still no use. How can I solve this problem? I have no clue...
It is successfully reading old files (2007 .xlsx) I didn't understand what is it that makes OLEDB to hide strings in Date column?
So you're saying that the new excel file is the issue? If so...
check the data in the file (particularly the first 8 rows in the employee name column)
copy the data from the new file to a file that is known to work
Accessing Excel Spreadsheet with C# occasionally returns blank value for some cells
Check out ABHI's answer in the above link (in particular points 1. and 2.)

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

Categories