Oledb cannot access file fix - c#

for a small project I need to create a DataTable filled with data from an Excelsheet. Im getting this data with using an Oledb connection. Sometimes other people are using this file on the server. So I'm getting the "The process cannot access the file because it is being used by another process"
private DataTable excelSelectStatement() {
try {
string par = this._colParameters.getParameterByName("SheetName", false, null).Value;
excelDataSet = new DataSet();
string ace12 = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + _selectionStatement + "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';";
using (OleDbConnection connection = new OleDbConnection(ace12)) {
OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + par + "$]", connection);
da.TableMappings.Add("Table", "TestTable");
da.Fill(excelDataSet);
}
}
catch (Exception e) { MessageBox.Show(e.Message); }
return excelDataSet.Tables[0];
}
Is there any way with completing this with Oledb?

Related

Problems trying to read dbf file in C#

I am trying to read a dbf file in C#, but first I had the error
System.InvalidOperationException: 'The provider' Microsoft.ACE.OLEDB.12.0 'is not registered on the local machine.'
Then I installed Microsoft Access Database Engine 2010 Redistributable and now I have the error
The Microsoft Access database engine cannot open or write to the file 'C:\Users\Emmanuel\Desktop\Proyectos\program'. It is already opened exclusively by another user, or you need permission to view and write its data.'
This is the code I'm using:
var constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
var sql = "select * from " + file;
var ds = new DataTable();
using (var con = new OleDbConnection(constr))
{
con.Open();
using (var cmd = new OleDbCommand(sql, con))
{
using (var da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Also I've tried this but I have this error
System.Data.Odbc.OdbcException: 'ERROR [HY000] [Microsoft] [ODBC dBase Driver] The external table is not in the expected format.'
string fullPath = path + file;
string sConn = "Driver={Microsoft dBASE Driver (*.dbf)};SourceType=DBF;SourceDB=" + path + ";Exclusive=No; NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
using (OdbcConnection dbConn = new OdbcConnection(sConn))
{
dbConn.Open();
OdbcCommand oCmd = dbConn.CreateCommand();
oCmd.CommandText = "SELECT * FROM " + fullPath;
/* Load data to table */
DataTable dt1 = new DataTable();
dt1.Load(oCmd.ExecuteReader());
dbConn.Close();
}

Is it possible to read and display a large number of > 230 thousand records excel data to the datagrid using oledb?

I have a problem with large amounts of excel data and need to display it in the datagrid, if the data is small this code works but is not effective for large amounts of data and has to wait a long time. is there a brilliant way to solve this problem?
this code
Stopwatch sw1 = Stopwatch.StartNew();
String path = "D:\\test.xlsb";
String sheet = "Sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path+
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + sheet + "$]", con);
try
{
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
datagrid1.ItemsSource = (System.Collections.IEnumerable)data.DefaultView;
con.Close();
sw1.Stop();
Console.WriteLine("Time taken for excel roots: {0} ms", sw1.Elapsed.TotalMilliseconds);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

C# Import Excel Data to SQL Table

I am trying to use a method I pulled off of CodePlex, which exports data from Excel into a SQL table. I have made some minor code adjustments, but I still can't seem to get the data to import. Does anyone see anything glaringly wrong with my syntax? Thanks.
static void Main(string[] args)
{
importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx");
}
public static void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "Name";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select Name,EmployeeID from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + excelfilepath + ";Extended Properties=" + "\"excel 8.0;hdr=yes;\"";
//MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'");
string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false";
//<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" />
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlcmd.Connection.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
The problem is here:
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
The while (dr.Read()) block is useful if you are iterating over the results one-by-one.
But it's not you who is iterating over the results. You want the bulk copy operation to do the iterating.
Simply replace it with
bulkcopy.WriteToServer(dr);
This should work for you.
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
For more info, see the links below.
https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh
http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/
As you can tell, there are MANY ways to do what you want to do.

importing excel to sql c#

I have been trying to import an excel table into my sql database. I have tried this example:
void importdata(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "tTableExcel";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have
string myexceldataquery = "select student,rollno,course from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = "server=mydatabaseservername;userid=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
My programming is not very good and I cannot make it work.
There is nothing wrong with the SQL connection (the db is cleared after running the program). But I am not able to get any information into the database.
My excel file is called test.xlsx and is stored in D:\Users\Haners. My database tabe is called Test. How can I make my program import the information in the excel file to the database???
Previous Code :
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
New Code :
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.BatchSize=100;
bulkcopy.WriteToServer(dr);
Hope this help to resolve your issue. Happy coding. cheers

Read Excel File Data From OleDbConnection

I'm currently facing a problem whereby I don't know how to fix it.
I upload my precompiled project into IIS. Here is my purpose of this page:
User upload a excel file into a folder in the server. ex #"~/PlanQuantityFile/". It did upload successfully.
Problems faced:
It stops when my scripts trying to open the excel file (for extract data purpose) without showing any errors. At line 881 as shown in the image.
Here is few area I had seek for but it still couldn't solve my problem.
Possible Solution:
connection open but never close, so run out of connection. (but I did close it and the scripts stop running before the close statement)
32 bit program calling 64 bit office. (I had limited knowledge on hardware field, don't know what should I do to troubleshoot here)
permission problem. Need to set the permission of ASP.NET account. (I still finding object names for ASP.NET account)
Thanks for anyone who trying to help. Your advice is invaluable.
OleDbConnection oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SaveLocation + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
OleDbConnection connExcel = oledbConn;
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of Sheet
try
{
connExcel.Open();// It stops here without showing errors.
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
The following code returns a datatable for selected filelocation source. Remember to rename the sheetname to "Sheet1".
Use Namespace: using System.Data.OleDb;
Function::::
public DataTable GetExcelinDatatable(string filelocation)
{
DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter("select * from [SHEET1$]", con);
da.Fill(dt);
con.Close();
return dt;
}
you can use mentioned function to read the Excel file you have to just pass the path of excel file
private List<DataTable> readExcel(string strXLS)
{
//DataTable dtExcel = getExcelSheetTable();
List<DataTable> SheetsData = new List<DataTable>();
DataTable dtExcel = new DataTable();
DataTable SocialMediaExcel = new DataTable();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLS + ";Extended Properties=Excel 12.0;";
try
{
OleDbDataAdapter adpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connStr);
adpt.Fill(dtExcel);
SheetsData.Add(dtExcel);
}
catch (Exception ex)
{
throw ex;
}
return SheetsData;
}

Categories