Excel OleDb C# - Cannot select range if worksheet has special characters - c#

I have run into a snag when reading info from a workbook in excel that contains a "#" in the name of the sheet. I am able to select the WHOLE worksheet but not a range in the worksheet.
Code:
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = "C:/TestExcel/TestWorkbook.xlsm";
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [Sheet #1$A1:A22]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
}
}
}
And the following queries work just fine.
comm.CommandText = "Select * from [Sheet #1$]";
comm.CommandText = "Select * from [Sheet2$A1:A22]";
I get the following exception saying it cannot find the table in question.
The Microsoft Office Access database engine could not find the object 'Sheet .1$A1:A22'.

Related

Webform only reads headers from a group Excel Files due to the Tab Name

I am building an app to read measurement data (saved as .xls files on our network) from comparators throughout our facility via a Webform. When I query this group of files I only retrieve the headers. My code (pretty standard) will read any other Excel file I can find. I tried to remove a file from the network and save it locally, as well as rename and save it from office 2016. Note - these are .xls files and I can't change that.
** - I just discovered that there are named ranges with the same name as the file. The results I am getting are just the values in the named range and not the data from the workbook.
Here is an example of how they are named (autogenerated) "R87_1RCR0009654S_COIN"
If I rename or remove the named range this works fine.
Is there a way I can change my select statement to read these?
Here is a code sample, not sure there if there is a change I can make here to read these files.
private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
string conStr, sheetName;
conStr = string.Format(Excel03ConString, info.FullName, "YES");
string fullPathToExcel = info.FullName;
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
}
}
}

How To skip 15 rows in excel (take out the header)?

I Want to skip a few rows in an excel file, 15 rows(A1 to A14) to be able to import in sql server... But What I'm finding in internet doesn't work with me, I was thinking if you guys could take a look in my code
protected void Upload_Click(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
string filepath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.FileName);
string filename = Path.GetFileName(filepath);
FileUpload1.SaveAs(excelPath);
string ext = Path.GetExtension(filename);
String strConnection = #"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$]", excelConnection);
excelConnection.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from [rptListaMovs_4$] ", strConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
sqlBulk.DestinationTableName = "Dados";
sqlBulk.ColumnMappings.Add("Data Mov", "Data Mov.");
sqlBulk.ColumnMappings.Add("Data Valor", "Data Valor");
sqlBulk.ColumnMappings.Add("Descrição do Movimento", "Descrição do Movimento");
sqlBulk.ColumnMappings.Add("Valor em EUR", "Valor em EUR");
sqlBulk.WriteToServer(dReader);
}
excelConnection.Close();
}
I already tried put the "IEnumerable" but it didn't work, I probably did it wrong.
If you know you always want to skip exactly the first 14 rows and start your query importing at A15, then you can write your SQL query like this:
Select * from [rptListaMovs_4$A15:G]
Replace G with the correct column Letter
P.S. Credit to this answer for this inspiration.
#MacroMarc and ADyson Helped me
Here's the solution:
OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$A15:D75]", excelConnection);
Insted of This:
OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$]", excelConnection);

Displaying values of excel Workbook in DataGridView C#

I need some help displaying values of excel in datagridview.
i manage to display values but some of the values are missing(columns,and values of rows).i have 1000 rows in my excel file and the data grid view is only displaying 333 items in it. and i have 148 number of columns but it only display some of it. can someone tell me what the problem is.
here is my code:
public partial class MainBagsakan : Form
[enter image description here][1]
String WOmain=#"C:\Users\tjjtabije\Desktop\TestExcelUpdater\TestUnoREFARM.xlsx";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\t-jjtabije\\Desktop\\TestExcelUpdater\\TestUnoREFARM.xlsx;Extended Properties='Excel 12.0 Xml;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text'";
private void WorkOrderTab()
{
string filePath = Path.GetFullPath(WOmain);
string extension = Path.GetExtension(filePath);
string conStr, sheetName;
conStr = string.Empty;
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(Excel07ConString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
using (OleDbConnection con = new OleDbConnection(Excel07ConString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * [" +sheetName+ "]";
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
WorkLoadDisp.DataSource = dt;
label1.Text = dt.Rows.Count.ToString();
}
}
}
}
It is unnecessary to open and close the connection twice as you are with the two separate using clauses. The first one simply gets the name of a worksheet sort of, as a named range could also be returned. I simply put all the code into a single group and it seems to work as expected.
Added a missing FROM to the select statement:
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
The changes I made are below...
using (OleDbConnection con = new OleDbConnection(Excel07ConString)) {
using (OleDbCommand cmd = new OleDbCommand()) {
using (OleDbDataAdapter oda = new OleDbDataAdapter()) {
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
//con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
WorkLoadDisp.DataSource = dt;
label1.Text = dt.Rows.Count.ToString();
}
}
}
Hope this helps.

Can't Find Worksheet

I am trying to select the "Report Details" worksheet from my excel file. However, I am having trouble selecting it,
The Microsoft Jet database engine could not find the object 'Report Details'. Make sure the object exists and that you spell its name and the path name correctly.
if (fileExtension == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
cmd.CommandText = "SELECT * FROM [Report Details]"; //ERROR HERE
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
GridView1.DataSource = dtExcelRecords;
GridView1.DataBind();
Viewing my "Tables" in the dataset viewer, the connection string is able to access the file. The Report Details column is displayed as 'Report Details$'. I have tried entering it that way, but I am still getting an error.
Your question title says EXCEL/C# Cant Find Worksheet
Your post says I am trying to select the "Report Details" WORKSHEET from my excel file.
The error you are getting is
The Microsoft Jet database engine could not find the object 'Report Details'. Make sure the object exists and that you spell its name and the path name correctly.
Solution
You are missing a $ sign
Try this (TRIED AND TESTED)
cmd.CommandText = "SELECT * FROM [Report Details$]";
I was able to get the tabel name throuh dtExcelSheetName
cmd.CommandText = "SELECT * FROM [" + con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1][2].ToString() + "]";
It is working now.

Query excel sheet in c#

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.

Categories

Resources