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].
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 am using the ACE OLEDB connection string to connect to an excel file. I've noticed my query (see example below) that returns the column schema takes longer to run when the worksheet has more rows of data on it.
For some of my larger worksheets (200k rows) it is taking around 10 seconds for the header schema to be returned. It there a way to speed this up or a better way to get the column headers?
string connectionString = string.Empty;
connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1""", path);
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
DataTable dtSchema = new DataTable();
System.Diagnostics.Debug.WriteLine("Start: " + DateTime.Now.ToLongTimeString());
dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
new Object[] { null, null, WorksheetName, null });
System.Diagnostics.Debug.WriteLine("End: " + DateTime.Now.ToLongTimeString());
con.Close();
UPDATE
I tried rewriting this - turning Headers off and manually reading only the first row. It still takes around 10 seconds to process on my larger files (small ones still come back very quickly). Is there anything else I can try that might be able to get the header(first row) values quicker?
string connectionString = string.Empty;
connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};
Extended Properties=""Excel 12.0 Xml;HDR=NO;""", path);
DataTable dtSchema = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(String.Format("SELECT * FROM [{0}A1:II1]", WorksheetName),conn);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = command;
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dtSchema = dataSet.Tables[0];
}
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();
}
I have Excel file shown bellow
I want to read 1st read only all school names & school address & insert them in SchoolInfo table of mySql database.
After that I want to read data for each school & insert it in StudentsInfo table which has foreign key associated with SchoolInfo table.
I am reading excel sheet something like this.
public static void Import(string fileName)
{
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
var output = new DataSet();
using (var conn = new OleDbConnection(strConn))
{
conn.Open();
var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
if (dt != null)
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
var cmd = new OleDbCommand("SELECT * FROM [+"+sheet+"+]", conn);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter xlAdapter = new OleDbDataAdapter(cmd);
xlAdapter.Fill(output,"School");
}
}
}
Now I am having data in datatable of dataset, Now how do I read desired data & insert it in my sql table.
Try the following steps:
Reading from Excel sheet
First you must create an OleDB connection to the Excel file.
String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + path + ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection xlConn = new OleDbConnection(connectionString);
xlConn.Open();
Here path refers to the location of your Excel spreadsheet. E.g. "D:\abc.xls"
Then you have to query your table. For this we must define names for the table and columns first. Click here to find out how.
Now create the command object.
OleDbCommand selectCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", xlConn);
Now we have to store the ouput of the select command into a DataSet using a DataAdapter
OleDbDataAdapter xlAdapter = new OleDbDataAdapter();
objAdapter1.SelectCommand = selectCmd;
DataSet xlDataset = new DataSet();
xlAdapter.Fill(xlDataset, "XLData");
Save the data into variables
Now extract cell data into variables iteratively for the whole table by using
variable = xlDataset.Tables[0].Rows[row_value][column_value].ToString() ;
Write the data from the variables into the MySQL database
Now connect to the MySQL database using an ODBC connection
String mySqlConnectionString = "driver={MySQL ODBC 5.1 Driver};" +
"server=localhost;" + "database=;" + "user=;" + "password=;";
OdbcConnection mySqlConn = new OdbcConnection(mySqlConnectionString);
mySqlConn.Open();
Construct your INSERT statement using the variables in which data has been stored from the Excel sheet.
OdbcCommand mySqlInsert = new OdbcCommand(insertCommand, mySqlConn);
mySqlInsert.ExecuteScalar()
I have an excel sheet which i am uploading to sqlserver table using sqlbulkcopy, i have applied an index on database table so that duplicate entries are ignored but i also want to display the duplicate entries which were ignored in a grid view.
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]",connection);
//Sql Server Table DataTable
DataTable dt4=new DataTable();
SqlCommand cmd4 = new SqlCommand("select id,data from ExcelTable", con);
try
{
SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
da4.Fill(dt4);//sql table datatable
}
catch { }
//excelsheet datatable
DataTable oltlb = new DataTable();
OleDbCommand olcmd = new OleDbCommand("select id,data from [Sheet1$]", connection);
try
{
OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
olda.Fill(oltlb); //excel table datatable
}
catch { }
var matched = (from table1 in dt4.AsEnumerable()
join table2 in oltlb.AsEnumerable() on
table1.Field<int>("ID") equals table2.Field<int>("ID")
where table1.Field<string>("Data") == table2.Field<string>("Data")
select table1);
DataTable dthi5 = new DataTable();
dthi5 = matched.CopyToDataTable();
GridView1.DataSource = dthi5;
GridView1.DataBind();
GridView1.DataSource = matched.ToList();
ERROR:
Specified cast is not valid.
table1.Field("ID") equals table2.Field("ID")
It would appear that the ID field in one of your tables is not an int.
Rather than one or both of us guessing, try inspecting the data type of the first column in both tables (oltlb and dt4) to see which has the non-integer data type. It may in fact be both.
Here's the thing: even if the value of a string is a numeric literal, you can't cast a string to an int. You'd have to use Int32.Parse or Convert.ToInt32 to convert. So if one of your tables has a string type for the ID column, you would express it like this:
table1.Field<int>("ID") equals Convert.ToInt32(table2.Field<string>("ID"))
If both of the tables have a string ID field, you could just express it this way:
table1.Field<string>("ID") equals table2.Field<string>("ID")