prevent Excel sheet opening on OLEDBCommand query - c#

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

Related

Use Excel Trim in C#

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

Read row number from Excel sheet using OLEDB Object

I am using OLEDB object to read an Excel file and return data in a datatable. The following Excel sheet has two columns, which imported, but I want to read the Excel row number as well, with my data.
This is the code I am using to read the Excel file:
private DataTable ImportExcel2007(String strFilePath)
{
if (!File.Exists(strFilePath)) return false;
String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + strFilePath + ";"
+ "Extended Properties='Excel 8.0;HDR=Yes'";
OleDbConnection connExcel = new OleDbConnection(strExcelConn);
OleDbCommand cmdExcel = new OleDbCommand();
try
{
cmdExcel.Connection = connExcel;
//Check if the Sheet Exists
connExcel.Open();
DataTable dtExcelSchema;
//Get the Schema of the WorkBook
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
//Read Data from Sheet1
connExcel.Open();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
//Range Query
//cmdExcel.CommandText = "SELECT * From [" + SheetName + "A3:B5]";
da.SelectCommand = cmdExcel;
da.Fill(ds);
connExcel.Close();
return ds.Table[0];
}
catch
{
return null;
}
finally
{
cmdExcel.Dispose();
connExcel.Dispose();
}
}
I can manage it by incremented number with new column in data table, but can I apply a WHERE clause with a SELECT statement to return data from different row numbers (where applying an incremented row number may fail)?
Unfortunately, OLEDB doesn't allow you to select based on row number. You can use something like this:
int rowNum = 0;
foreach (DataTable dt in ds.Tables)
{
dt.Columns.Add("RowNum",typeof(Int32));
rowNum = 1;
foreach (DataRow dr in dt.Rows)
{
dr["RowNum"] = rowNum++;
}
}

How to choose a value from cell in Excel

How can I choose correctly value from cell in Excel? I know that my problem is with command for select cell.
My actually scripts:
List<string> wsList = new List<string>();
DataTable schemaTable;
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string name;
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}
OleDbConnection con = new OleDbConnection(_ConnectionString);
try
{
con.Open();
// Get schematable name from excel file
schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow row in schemaTable.Rows)
wsList.Add(row.Field<string>("TABLE_NAME"));
name = wsList[0];
// Select values from cell in excel
string strCmd = "SELECT J38 FROM [" + name + "]"; // I think that here is my main problem
// Command for select value
OleDbCommand cmd = new OleDbCommand(strCmd, con);
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
UniqueValue.money.Add(double.Parse(da.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
Image where you can watch what I need select: (Merged-Cell)
Debug:
For one or more required parameters were not found, no value
Merged cells and data adapters don't mix. If this is a one-off, copy the values from the original worksheet into an empty workbook and unmerge the cells, do any other cleanup manually. If this is a production process that needs to be repeated, and is high-volume, consider writing a VBA macro in the workbook to do the copypasta/cleanup process for you.

Unable to read Excel worksheet with OLEDB driver

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"];

data import from excel facing an issue

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>

Categories