I am reading the excel file using C# and below is the code which is working as expected EXCEPT that every time i run the app, I have to close the excel file otherwise I get the below error message:
The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data..
my question is: is there a way i close the excel file once i am done reading?
public static DataTable LoadExcelWorkbook(string workbookName)
{
OleDbConnection connection;
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", EXCELFILENAME);
string query = String.Format("select * from [{0}$]", workbookName);
using(OleDbConnection conn = new OleDbConnection(connectionString))
{
connection = new OleDbConnection(connectionString);
connection.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
DataTable myTable = dataSet.Tables[0];
dataAdapter.Dispose();
connection.Close();
dataSet.Dispose();
//CLOSE THE EXCEL FILE?????????
if (myTable != null)
return myTable;
return null;
}
}
use sheet1 name instead of workbook name
Related
I need to fetch a row value from an excel sheet in data grid view in winform.
I’m able to display the entire excel sheet in the datagridview. But, I need to display particular rows in the grid based on a current date condition.
public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$] WHERE Date=#date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("#date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}
Thanking you in advance
What seems to be happening here is that the Date parameter is not being honored, as you are getting back all of the rows. So, I used Google to figure out how to properly add parameters when using OleDbConnection. I found this:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement
Source: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters
Using the example on that page, try changing your code to this:
string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$] WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
Please note that i've not tested this, so I can't promise it will work. But, the main point is... the answer is out there! You just need to go looking for it.
Hi I am having some issues reading a CSV file with the Jet Database engine. I get this message:
The Microsoft Jet database engine cannot open the file 'C:\Users\mikec\Desktop\'. It is already opened exclusively by another user, or you need permission to view its data.
I have permission to access this folder and file. I have also tried putting in my Visual Studio project and still get the same error. This is my code
string path = #"C:\Users\mikec\Desktop\Book1.csv";
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"Excel 8.0;HDR=Yes;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
OleDbConnection con = new OleDbConnection(connString);
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, con);
try
{
//fill the DataTable
dAdapter.Fill(dTable);
}
catch (InvalidOperationException e)
{
}
I'm confused to why this is happening I've looked around the Internet and cannot find a solution.
It would be great if anyone out there could point me in the right direction.
Thanks.
I need to connect to a .dbf file in visual Studio using C# and populate a data table. Any ideas? I can currently view the tables in Visual Fox Pro 9.0
Code I have tried and failed, keep getting
External table is not in the expected format.
private OleDbConnection conn;
private OleDbCommand cmd;
private OleDbDataReader dr;
private string sqlStr = "";
private DataSet myDataSet;
private OleDbDataAdapter myAdapter;
void test2()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\PC1\Documents\\Visual FoxPro Projects\\;Extended Properties=DBASE IV;");
conn.Open();
sqlStr = "Select * from Clients.dbf";
//Make a DataSet object
myDataSet = new DataSet();
//Using the OleDbDataAdapter execute the query
myAdapter = new OleDbDataAdapter(sqlStr, conn);
//Build the Update and Delete SQL Statements
OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdapter);
//Fill the DataSet with the Table 'bookstock'
myAdapter.Fill(myDataSet, "somename");
// Get a FileStream object
FileStream myFs = new FileStream
("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);
// Use the WriteXml method of DataSet object to write XML file from the DataSet
// myDs.WriteXml(myFs);
myFs.Close();
conn.Close();
}
This code worked for me!
public DataTable GetYourData()
{
DataTable YourResultSet = new DataTable();
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\");
// if including the full dbc (database container) reference, just tack that on
// OleDbConnection yourConnectionHandler = new OleDbConnection(
// "Provider=VFPOLEDB.1;Data Source=C:\\SomePath\\NameOfYour.dbc;" );
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from CLIENTS"; // dbf table name
OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(YourResultSet);
yourConnectionHandler.Close();
}
return YourResultSet;
}
Visual FoxPro DBFs are NOT dBase IV DBFs, and as such are unreadable by most versions of Microsoft Access's Jet database engine. (MSDN has some specifics, if you care.)
You'll need to either export the DBF from FoxPro into an actual dBase format, or you'll need to have C# open it using the Visual FoxPro OLEDB provider.
Once you have the provider installed, you'll need to change the "Provider" argument of your connection string to the following, assuming your DBF is in that folder.
Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\;
(Use an #"" string format; you missed a slash in the code sample, between PC1 and Documents.)
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.
How to read the xls and xlsx files using c# with OpenXML format Without using the OLEDB connection. I am looking for Open XML format procedure.
Below is the code in which I used the OLEDB preocedure. But I am looking for OpenXML format.
public static DataTable ConvretExcelToDataTable(string FilePath)
{
string strConn = string.Empty;
if (FilePath.Trim().EndsWith(".xlsx"))
{
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", FilePath);
}
else if (FilePath.Trim().EndsWith(".xls"))
{
strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", FilePath);
}
OleDbConnection conn = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;
DataTable dt = new DataTable();
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand(#"SELECT * FROM [Sheet1$]", conn);
cmd.CommandType = CommandType.Text;
da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
Console.ReadLine();
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
}
return dt;
}
Requirement is to implement the above conversion in OpenXML format. Thanks.
You'll want the OpenXml SDK for the xlsx:
http://www.microsoft.com/en-gb/download/details.aspx?id=30425
But for the XLS, you won't be able to use this the XLS format is not based on xml.
I use the NPOI library for accessing older files:
http://npoi.codeplex.com/
The NPOI library also supports xlsx, so this would give you a consistent way of accessing them. Downside is you'll have to loop through sheets/rows/columns manually, and build up the dataset which will probably affect performance if you have large workbooks. If you want to use queries to access the data, OLEDB is the only method I've found.
If you have Excel installed, you could use Microsoft.Office.Interop.Excel;
http://support.microsoft.com/kb/302084
Remove \ from the connection string. You can give as below.
conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+filepath.ToString() + ";Extended Properties=Excel 12.0 Xml;");