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();
Related
I am working with c# in WPF. Pulling data into datatables. Everything was working OK until I changed to using the actual worksheet name as pulled from the sheet via a foreach (worksheet in workbook) loop.
Now that I have the actual worksheet name and include it in my OLEDbCommand, the worksheet open on the screen.
I would like to prevent/stop the Excel file from opening on the screen as it is not needed nor desired.
Below is the connection string and the beginning of the try/catch that has the commands and query.
string con_string = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
try
{
OleDbConnection con = new OleDbConnection(con_string);
con.Open();
//OleDbCommand ocon = new OleDbCommand("SELECT * FROM [" + myMonth + " " + year + "$]", con);
OleDbCommand ocon = new OleDbCommand("SELECT * FROM [" + myWorkSheet + "$]", con);
OleDbDataAdapter sda = new OleDbDataAdapter(ocon);
sda.Fill(data);
dGrid.DataContext = data;
}
If I revert back to the commented out line using the myMonth and year variables (created in a SelectionChanged method from a Calendar object), the spreadsheet does not open.
The following is the code that access and creates the list of actual worksheets I use to populate a comboBox dropdown.
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(fullFilePath);
String[] excelSheets = new String[excelBook.Worksheets.Count];
int i = 0;
foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)
{
excelSheets[i] = wSheet.Name;
cmbBox2.Items.Add(excelSheets[i]);
i++;
}
Add these two lines-
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
below this line-
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
I have an excel file with one worksheet. I'm using MicroSoft.Office.Interop.Excel to read this file and then perform further execution.
Here is my code:
connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;";
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = null;
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
But, worksheet is not in the data table object.
Where you have mentioned the table(WorkSheet) name ??
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
//Get the First Sheet Name
string firstSheetName = schemaTable.Rows[0][2].ToString();
//Query String
string sql = string.Format("SELECT * FROM [{0}],firstSheetName);
Refer here MSDN
In case if you want to play around refer Reading Excel files from C#
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + "; Extended Properties=Excel 12.0;");
//After connecting to the Excel sheet here we are selecting the data
//using select statement from the Excel sheet
oconn.Open();
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
string tbstrat = "M1000";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oconn;
cmd.CommandText = "select * from [" + firstSheetName + "B8:" + tbstrat + "]";
OleDbDataAdapter adap = new OleDbDataAdapter();
DataTable dt = new DataTable();
adap.SelectCommand = cmd;
adap.Fill(dt);
oconn.Close();
Even you can try this
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "NameHere");
DataTable data = ds.Tables["NameHere"];
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\";";
I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>
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);