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.
Related
I am writing a component in C# which returns data from an EXCEl spreadsheet using Microsoft.ACE.OLEDB.12.0. The spreadsheet contains cells with formulas and references to other spreadsheets within that workbook. These cells return no data to the DataTable. See example below.
OleDbConnection OleDBconn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"",InputFile));
OleDbCommand OleCommand = new OleDbCommand();
OleCommand.Connection = OleDBconn;
OleDBconn.Open();
dtXLS = OleDBconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(OleCommand);
OleCommand.CommandText = string.Format(#"SELECT [Column] From [Sheet1$]");
adp.SelectCommand = OleCommand;
adp.Fill(dt);
Column contains cells with formulas and references to other worksheets in the workbook. So dt[0][Column] is null when it should have a value. The cell in the spreadsheet contains the below reference
=dd!B2
here is something that you can try in regards to filling and returning the DataTable
//call the method this way
var someDataTable = ExecuteDataSet("SELECT * FROM [Sheet1$]", InputFile);
public static DataTable ExecuteDataSet(string sql, string InputFile)
{
using (DataSet myDataset = new DataSet())
using (OleDbConnection OleDBconn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"",InputFile));
using (OleDbCommand cmdSelect = new OleDbCommand(sql, OleDBconn))
{
try
{
OleDBconn.Open();
dtXLS = OleDBconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//if you need to return this change the method signature to out param for this
new OleDbDataAdapter(cmdSelect).Fill(myDataset);
}
catch (Exception ex)
{
//Show a message or log a message on ex.Message
}
return myDataset.Tables[0];
}
}
How can I get list name from Excel file? My actual script for read from Excel is this:
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string name = "PP_s_vypocty"; // I actually using manualy name for read, but i want extract name from file.
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);
string strCmd = "SELECT J38 FROM " + name;
OleDbCommand cmd = new OleDbCommand(strCmd, con);
try
{
con.Open();
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();
}
I want to extract name from excel list without manually definition.
You can use OleDbConnection.GetSchema that return a datatable with the list of tables (excel worksheet in your case) that the database contains
I'm using Microsoft.ACE.OLEDB.12.0 to connect to Microsoft excel file and fetch data from it. I write my codes in C# language using Visual Studio 2012.
here is my code:
public DataTable getData(string fileName, string sheetName)
{
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"
+ fileName
+ "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
errorCode = ErrorDefinition.ERROR_NOERROR;
errorMessage = "";
DataTable dt = new DataTable();
try
{
string query = "SELECT * FROM [" + sheetName + "]";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, con);
dataAdapter.Fill(dt);
}
catch (Exception exp)
{
errorCode = ErrorDefinition.ERROR_OLEDBERROR;
errorMessage = exp.Message;
}
return dt;
}
The problem is that dt does not contain the first row of the specified sheet in file. What's wrong with it?
In your connection string you use the setting "HDR=YES", this means that the first row from your Excel file is treated by OleDb as the row containing the table's field names represented by the current sheet.
Using "HDR=NO" indicates to OleDb that the first row contains data and the column names are automatically named, in progression. as "F1", "F2", "F3" etc....
Try HDR=NO in connection string
I am trying to pull a bunch of data from a spreadsheet, however I am not able to make a successful connection in my C# code. B
Below is the connection string and the code that I am using to make the connection. The goal of the program is to pull the data from the spreadsheet and deposit it into a SQL database. I cannot get past the connection.open() command, however without receiveing this error message:
"External table is not in the expected format"
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [SQL AgentUnique ID Test Load$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
counter++;
//Access db values
string compCode = "";
string agId = "";
string fName = "";
string lName = "";
string nameSuffix = "";
compCode = reader.GetValue(0).ToString();
agId = reader.GetString(1);
fName = reader.GetString(2);
lName = reader.GetString(3);
nameSuffix = reader.GetString(4);
sqlComm.Parameters.Add(companyCode);
sqlComm.Parameters.Add(agentID);
sqlComm.Parameters.Add(firstName);
sqlComm.Parameters.Add(lastName);
sqlComm.Parameters.Add(suffix);
//Initialize connection objects
cm = Dts.Connections["QUAHILSQ03"];
sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new SqlCommand("AgentResourcesU01.dbo.sp_AgentIdAprCheck", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
//Execute stored procedure
sqlComm.ExecuteNonQuery();
}
reader.Close();
connection.Close();
OleDbConnection.ReleaseObjectPool();
}
For *.xlsx, you need the Ace drivers: Microsoft.ACE.OLEDB.12.0
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;
Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
Wrote this a long while back. It's in WebForms, but the .cs file shows you want you need:
converting an excel spreadsheet to a dataset, datatable and multi-dimensional array
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+FileToConvert+";Extended Properties=Excel 8.0;";
try
{
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
//this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
adapter.Fill(ds);//now you have your dataset ds now filled with the data and ready for manipulation
// do stuff
}
I need to open an excel sheet from a particular location (d:\temp\emp.xls) and then bold the column headers and save the file.
I am trying to do it but not getting how to open the file and access the 1 row and make them as bold in c#?
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; data source=c:\customers.xls; Extended Properties=Excel 8.0;";
// Select using a Named Range
//string selectString = "SELECT * FROM Customers";
// Select using a Worksheet name
string selectString = "SELECT * FROM [Sheet1$]";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(selectString,con);
try
{
con.Open();
OleDbDataReader theData = cmd.ExecuteReader();
while (theData.Read())
{
Console.WriteLine("{0}: {1} ({2}) - {3} ({4})", theData.GetString(0),theData.GetString(1),theData.GetString(2),theData.GetString(3),theData.GetString(4));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Dispose();
}