I am using OLEDB to read the data from an Excel spreadsheet.
var connectionString =
string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "mySheet");
var data = ds.Tables["mySheet"].AsEnumerable();
foreach (var dataRow in data)
{
Console.WriteLine(dataRow[0].ToString());
}
Instead of passing an index to the DataRow to get the value of a column, is there anyway to retrieve the column by the name of the column header?
Try this code:
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0; HDR=YES", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "mySheet");
var data = ds.Tables["mySheet"].AsEnumerable();
foreach (DataRow dataRow in data)
{
Console.WriteLine(dataRow["MyColumnName"].ToString());
Console.WriteLine(dataRow.Field<string>("MyColumnName").ToString());
}
I added in 2 ways to access the data in the row via column Name.
Hope this does the trick!!
Modify your connection string to specify that you have headers in your excel file.
You can do this by setting the HDR value.
Refer this link to for various variations of connection string and build the one that suits your needs"
http://www.connectionstrings.com/excel/
Use a DataTable to have your data.
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + **EXCEL FILE PATH** + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbCommand cmd2 = new OleDbCommand("SELECT * FROM [**YOUR SHEET** $]", conn);
cmd2.CommandType = CommandType.Text;
DataTable outputTable2 = new DataTable("myDataTable");
new OleDbDataAdapter(cmd2).Fill(outputTable2);
foreach(Datarow row in outputTable2)
{
String s = row["yourcolumnheader"].ToString();
}
Related
I am getting list of excel files within specific directory as below
public void GetFilesList()
{
ListFiles = Directory.GetFiles(DefaultDirectory, "*.xlsx", SearchOption.AllDirectories);
foreach (string FilePath in ListFiles)
{
ImportExcel(FilePath);
}
}
then I am trying to add rows from each file within that directory into my datagridview as below
public void ImportExcel(string FilePath)
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
OleDbConnection Conn = new OleDbConnection(ConnStr);
OleDbDataAdapter DA = new OleDbDataAdapter("select * from [Sheet1$]", Conn);
DataTable dt = new DataTable();
if (dataGridView1.Rows.Count == 0)
{
DA.Fill(dt);
dataGridView1.DataSource = dt;
//Calculate record counts
L_Total_Rows.Text = "count: " + dataGridView1.Rows.Count.ToString("n0");
Conn.Close();
}
else
{
foreach (DataRow dr in dt.Rows)
{
dataGridView1.Rows.Add(dr);
dataGridView1.DataSource = dt;
}
}
}
my problem is that it import rows form one excel file only
it wont get into else condition it only get into the if condition then stops importing
another one question anyway to NOT use the sheet name at query [Sheet1$]? I don't know if it is possible the index of sheets ?
can I start importing the excel file form specific row like fourth row of excel file ?
How about you combine your result sets into one data table first:
DataTable dt = new DataTable();
using(OleDbDataAdapter a1 = new OleDbDataAdapter("select * from [Sheet1$]", Conn))
a1.Fill(dt);
using(OleDbDataAdapter a2 = new OleDbDataAdapter("select * from [Sheet1$]", Conn))
a2.Fill(dt);
the issue was solved by moving DataTable dt = new DataTable(); to the beginning of the class because each time I am calling ImportExcel(FilePath) method it will build new datatable so it will delete all old data and create new datatable and changed my method to below
public void ImportExcel(string FilePath)
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
OleDbConnection Conn = new OleDbConnection(ConnStr);
OleDbDataAdapter DA = new OleDbDataAdapter("select * from [Sheet1$]", Conn);
DA.Fill(dt);
DGV_Data.DataSource = dt;
//Calculate record counts
L_Rows_Count.Text = "Count: " + (DGV_Data.Rows.Count - 1).ToString("n0");
Conn.Close();
}
now there is a small problem still annoying me which is it will insert an empty row at datagriview between each imported excel file
I want to show data in datagridview in c# using from two source one from excel sheet and other from text file .I want to join these data source .For example if I get columns from Excel sheet excel1 excel2 AND Txt1 Txt2 from text file .Then I want to show result like excel1 excel2 Txt1 Txt2 in data grid view.
Current i can show data from excel file using below code.
private void button_cars_Click(object sender, EventArgs e)
{
String name = "Car List";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "c:\\Vehicle_List.xlsx" + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select CARID, BRAND, MODEL, FUEL, CC, YEAR From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridViewMain.DataSource = data;
}
I handle this situation like this
public DataTable mergeSheetAndTextFile()
{
String name = "Sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"D:\\YOURPATH\\List.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select col1,col2 From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
data.Columns.Add("Txt1Col", typeof(System.String));
string[] txtFileLines= File.ReadAllLines("c://YOURPATH//test.txt");
int count=0;
foreach (DataRow row in data.Rows)
{
if(count<txtFileLines.Length){
row["Txt1Col"]=txtFileLines[count]
count++;`enter code here`
}
}
}
I have excel file with 2 tables. I need to read this tables and get all the values from this tables. But all for what I have is:
OleDbConnection cnn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MigrateExelSql\Include\TestDb.xlsx; Extended Properties=Excel 12.0;");
OleDbCommand oconn = new OleDbCommand("select * from [Sheet1$]", cnn);
cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
And I don't uderstand what I need to write for get the all values from Username and Email tables. Here is the .xlsx table TestDb Please can somebody help me, because I'm googling the second day and I have no idea for what I must to do.
And when I try to get values by this method it return me an error:
var fileName = string.Format("{0}\\Include\\TestDb.xlsx", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "Username");
var data = ds.Tables["Username"].AsEnumerable();
foreach (var item in data)
{
Console.WriteLine(item);
}
Console.ReadKey();
One more Edit:
string con =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MigrateExelSql\Include\TestDb.xlsx; Extended Properties=Excel 12.0;";
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);
}
}
}
Console.ReadKey();
This will read only first column, but when I try to read dr[1] it will return error: Index was outside bound of the array.
Your xlsx file contains only one sheet and in that sheet there is only one column.
A sheet is treated by the OleDb driver like a datatable and each column in a sheet is considered a datacolumn.
You can't read anything apart one table (Sheet1$) and one column (dr[0]).
If you try to read dr[1] then you are referencing the second column and that column doesn't exist in Sheet1.
Just to test, try to add some values in the second column of the Excel file.
Now you can reference dr[1].
Any help what I am doing wrong here? if I am trying to read the only row for an example TestCaseName to case_1 then i'm getting the data of different row.
How can I make sure its only read what is being requested to read? and I am using the where clause but seems like does not filter it.
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", EXCELFILENAME);
string testCaseName = "case_1
string query = String.Format("SELECT * from [{0}$] WHERE TestCaseName=\"{1}\"", workbookName, testCaseName);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
DataTable myTable = dataSet.Tables[0];
TestCaseName Name Active Status etc...
----------------------------------------------------------------
case_1 Tom yes Completed etc...
----------------------------------------------------------------
case_2 John yes etc...
----------------------------------------------------------------
case_3 Jim yes etc...
----------------------------------------------------------------
case_4 Don yes etc...
----------------------------------------------------------------
case_5 Sam yes Visitor etc...
----------------------------------------------------------------
Here's the code I tested with. It appears to work perfectly. If your doesn't then I can only assume that your spreadsheet is not structured quite the same as mine.
string connectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
string testCaseName = "case_1";
string query = "SELECT * from [Sheet1$] WHERE TestCaseName=\"" + testCaseName + "\"";
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, conn))
{
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dt = ds.Tables[0];
}
conn.Close();
}
I want to read Excel file in c# using following code
string excelFileName = "Book2.xls";
string excelConnectString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Book2.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
//string excelConnectString = #"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " + excelFileName + ";" + "Extended Properties = Excel 8.0; HDR=Yes;IMEX=1";
OleDbConnection objConn = new OleDbConnection(excelConnectString);
OleDbCommand objCmd = new OleDbCommand("Select * From [Sheet1$]", objConn);
OleDbDataAdapter objDatAdap = new OleDbDataAdapter();
objDatAdap.SelectCommand = objCmd;
DataSet ds = new DataSet();
objDatAdap.Fill(ds);
Everything is working fine.Now my requirement is to read the excel file something like below
SELECT A,B,D From [Sheet1];
The Select-command should look like this if you want to read A1 to D1:
SELECT * FROM [SHEETNAME_HERE$A1:D1]
Whole Code:
OleDbConnection con = new OleDbConnection(
"provider=Microsoft.Jet.OLEDB.4.0;data source="
+ XLS_FILE_NAME_AND_PATH_HERE
+ ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("SELECT * FROM [" + SHEETNAME_HERE + "$A1:D1]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
DataView dvEmp = new DataView(dsXLS.Tables[0]);
dataGridView1.DataSource = dvEmp;
DataTable Contents = new DataTable();
using (OleDbDataAdapter adapter = new OleDbDataAdapter("Select * From [Sheet1$]", objConn))
{
adapter.Fill(Contents);
}
Console.WriteLine(Contents.Rows[0][0]);
You can select a particular cell by passing the proper index.
You can just constuct use query like that:
SELECT FirstName, LastName, Mobile FROM [Sheet1$]
i.e. use first row values as column names.