Hello well i try to import a Excel document into my DataGridView in C#.
So far it worked but there is a Column with Data in it i need to 'sort'.
If this was simple i would do "WHERE test > 0" in the OleDbDataAdapter query.
But.. The name of the Column is changing with each document and i need to use it often. So far i got this :
private void button1_Click(object sender, EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Users\\Test\\Desktop\\Test.xls;" +
"Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Test$]", strConn);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
In the select i need to put a line witch state that the first 3 letters of the column is the same but the number that follow are not. Like:
QTA 12345,
QTA 13213,
QTA 92818.
Something like:
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Test$] WHERE [testColumn] > 0", strConn);
But then with the same first 3 letters and the last numbers who are random.
Can someone help me please?
I've tried some code and it works fine for me. Have a try:
OleDbConnection oleDbConnection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=D:\\Users\\name\\Desktop\\test.xls;" +
"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
oleDbConnection.Open();
//Get columns
DataTable dtColumns = oleDbConnection.GetSchema("Columns", new string[] { null, null, "Tabelle1$", null });
List<string> columns = new List<string>();
foreach (DataRow dr in dtColumns.Rows)
columns.Add(dr[3].ToString());
string colName = columns.Find(item => item.Substring(0,3) == "QTA");
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Tabelle1$] WHERE [" + colName + "] > 0", oleDbConnection);
da.Fill(ds);
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
oleDbConnection.Close();
Pay attention to changing the connection string to your needs.
You can trim the code, using LINQ:
string colName = (from DataRow dr in dtColumns.Rows where dr[3].ToString().Substring(0, 3) == "QTA" select dr[3].ToString()).ElementAt(0);
Related
somebody can i help me? I need import a sheet to DataGridView and later export to Excel. But i wish use the function TRIM before the import to DataGridView. My code:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = "C:\\Documents";
openFile.Filter = "Microsoft Excel |*.xls;*.xlsx;*.xls |All Files (*.*)|*.*|Text (*.csv)|*.csv";
if (openFile.ShowDialog() == DialogResult.OK)
{
txtFile.Text = openFile.FileName;
this.btnImp.Enabled = true;
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + openFile.FileName + ";" +
"Extended Properties=Excel 8.0;");
//HERE MY ASK
var excelApp = new Excel.Application();
excelApp.Range["A2:A460"].Formula = "=TRIM()";
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Plan1$]", conn);
da.Fill(ds);
vGrade.DataSource = ds.Tables[0];
conn.Close();
}
}
This code below doesn't works. I never worked with 'Microsoft.Office.Interop.Excel'
//HERE MY ASK
var excelApp = new Excel.Application();
excelApp.Range["A2:A460"].Formula = "=TRIM()";
The error is : An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in SisE400.exe Additional information: Exception the HRESULT: 0x800A03EC
I just want to TRIM "A2:A460" from my sheet excell. How do i do it? What's the syntax?What's the subject? Please help me.
Try this... worked for me..
I have created two columns "Col 1" and "Col 2"
private static void ReadExcel()
{
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=Z:\\Codes\\Test1.xls;" +
"Extended Properties=Excel 8.0;");
var excelApp = new Microsoft.Office.Interop.Excel.Application();
OleDbDataAdapter da = new OleDbDataAdapter("Select LTRIM(RTRIM([Col 1])) AS [Col 1],LTRIM(RTRIM([Col 2])) AS [Col 2] From [Plan1$]", conn);
da.Fill(ds);
// vGrade.DataSource = ds.Tables[0];
conn.Close();
}
It seems like you are trying to use TRIM() to trim values and save them back to the original location. The way excel formulas work, you'd need to use a different range to store the trimmed value, and reference the original cell in that formula. Something like:
excelApp.Range["B2"].Formula = "=TRIM(A2)";
Note that 1) this puts the trimmed value in a different column (overwriting whatever was there) and 2) it works for a single cell - I don't know of you can apply a formula to a range and it will replicate automatically.
An easier method may be to trim the data in C# instead of using Excel interop:
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + openFile.FileName + ";" +
"Extended Properties=Excel 8.0;");
using(OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Plan1$]", conn))
{
da.Fill(ds);
}
foreach(DataRow dr in ds.Tables[0].Rows)
dr[0] = dr[0].ToString().Trim(); // trim the value in the first column and save it back
vGrade.DataSource = ds.Tables[0];
conn.Close();
Hello i need to "merge" 2 DataTables in one datagridview and i can't handle it. So far i have sth like this code below and now i want to place another datatable(it have the same number of columns) just below this without any separation(just like adding new rows). For example the code below returns 3 rows so i want my data from another source to appear starting in row 4, how can i do this ? Anyone can help ?
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\test.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
Try this..
Add a new DataTable for another datasource and then add new datarow to first datatable (data)
Then add the columns and relevant data to it.
Do all this after filling first datatable from db.
take reference from this
http://www.codeproject.com/Questions/670856/how-to-add-new-row-and-new-values-in-gridview-in-a
This is how i am import my Excel file:
stirng file = "c:\myFile.xlsx";
DataGridView dgvIM;
private void Import()
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
file +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dgvIM.DataSource = data;
}
What i want to do is import my Excel file but with specific condition, my second column contain several groups of strings ("First", "Second" etc..) and i want to add only the column with name "First" and not the whole list.
How can i do that ?
Just use a where condition on the sql command like this
string cmdText = "Select * From [" + name + "$] WHERE secondColumnName = 'First'";
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand oconn = new OleDbCommand(cmdText con))
{
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dgvIM.DataSource = data;
}
Note that in your connectionstring you specify HDR=YES, this means that the first non blank line of your excel sheet contains headers that are interpreted as column names. You should update your query setting the correct column name in the WHERE condition
EDIT In response at your comments below, if you want to retrieve every row where AGE is 12 the query becomes
string cmdText = "Select * From [" + name + "$] WHERE Age = 12";
My excel simulation needs to be imported into C#, after which the table needs to be able to be refreshed. The simulation revolves around randomly generated numbers. The random numbers are the only columns that change, since I'm doing that manually. The surrounding columns should update with the random numbers. I have tried various things but no luck so far.
Also, as the code is now, the
adp.Update(excelDataSet);
command invokes the error "Update requires a valid UpdateCommand when passed DataRow collection with modified rows." The table is only loaded into the gridview at all when it is commented out.
Here is my code atm. Thanks in advance.
string fileName = #"C:\simulation.xlsx";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;READONLY=FALSE\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [SHEET1$]", con);
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
DataSet excelDataSet = new DataSet();
adp.Fill(excelDataSet);
for (int i = 0; i < 29; i++)
{
excelDataSet.Tables[0].Rows[i][1] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][6] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][8] = Math.Round(r.NextDouble(), 2);
}
adp.Update(excelDataSet);
gridview.DataSource = excelDataSet.Tables[0];
con.Close();
Add a line that build a OleDbCommandBuilder
....
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adp);
adp.UpdateCommand = cb.GetUpdateCommand();
....
This will create the UpdateCommand in the OleDbDataAdapter for you, (can be used also for the InsertCommand and DeleteCommand)
Hi there I am trying to establish a connection to a data source and extract the information and display it in a grid view. The problem is that i always get null value for ada. Is it possible to have mistyped the query or is there something wrong with the adapter?
Furthermore I am using the myInt variable to insert different data sources because i hav to process more than one file, maybe this could be problematic as well.
try
{
//establish connectioin
OleDbConnection conn = new OleDbConnection(("provider=Microsoft.Jet.OLEDB.4.0; " + ("data source=" + myInt + ";" + "Extended Properties=Excel 8.0;")));
OleDbDataAdapter ada = new OleDbDataAdapter("SELECT * FROM MarkingSheet$]", conn);
DataSet ds = new DataSet();
ada.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
conn.Close();
}
ANSWER
Thats what worked for me
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + myPath + ";Excel 12.0;HDR=YES;"); ;
conn.Open();
OleDbDataAdapter ada = new OleDbDataAdapter("select * from [Marking Sheet$]", conn); ;
DataSet ds = new DataSet();
ada.Fill(ds);
Change the sql to
"SELECT * FROM [MarkingSheet$]"
since there's a missing opening bracket.
The Fault in your code is that you havent opened a connection when you attempt to fill the Adapter. Your SQL Statement is also wrong. You may also wan wish to bind the DataTable to the DataGridView too like this :-
try
{
OleDbConnection conn = new OleDbConnection(("provider=Microsoft.Jet.OLEDB.4.0; " + ("data source=" + myInt + ";" + "Extended Properties=Excel 8.0;")));
OleDbDataAdapter ada = new OleDbDataAdapter("SELECT * FROM [MarkingSheet$]", conn);
DataSet ds = new DataSet();
conn.Open();
ada.Fill(ds.Tables[0]);
conn.Close();
BindingSource bs = new BindingSource();
bs.Datasource = ds.Tables[0];
dataGridView1.DataSource = bs;
}
catch(OledbException x)
{
// Handle Exception
}
EDIT **
Try Changing your connection string to :-
string connString = "provider=Microsoft.Jet.OLEDB.4.0;Data source=" + myInt + ";Extended Properties=Excel 8.0;HDR=Yes;IMEX=1\";";