OleDBException when reading an open excel file - c#

I have an excel file and an oledb connection to it. When reading data while file is opened in windows, it throws the following error (at Adapter.Fill method).
However, the code runs fine when file is not opened manually.
private System.Data.DataSet GetExcelData()
{
// Create new DataSet to hold information from the worksheet.
System.Data.DataSet objDataset1 = new System.Data.DataSet();
DataTable dt = new DataTable();
try
{
string path = ConfigurationManager.AppSettings["ExcelFilePath"];
//string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection objConn = new OleDbConnection(connectionString);
objConn.Open();
//String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] = 'aa'";//Status
String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] IS NULL OR [Status]='SubReport'";//Status SubReport
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Fill the DataSet with the information from the work sheet.
objAdapter1.Fill(objDataset1, "ExcelData");
objConn.Close();
}
catch (Exception ex)
{
throw ex;
}
return objDataset1;
}
The error message is

Assuming you don't need to write to the file, try adjusting your connection string to include the read only mode (Mode=Read). I have that in all of mine (where I don't need to write to the file) and I've never had a problem reading from workbooks that are already open:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Mode=Read;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
I also don't tend to read Excel files as XML, so the Extended Properties for my connection strings are Excel 12.0;HDR=YES;IMEX=1;

Related

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;
}

C# GetOleDbSchemaTable. Name of first Excel Worksheet and its columns

try
{
string connectionString = string.Empty;
if (Path.GetExtension(fileName) == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Extended Properties=Excel 12.0;";
}
else
{
Debug.Print(connectionString);
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.Combine(Server.MapPath("~/Content"), fileName) + ";Extended Properties=Excel 8.0;";
//connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path.Combine(Server.MapPath("~/Content"), fileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
}
OleDbCommand selectCommand = new OleDbCommand();
OleDbConnection connection = new OleDbConnection();
OleDbDataAdapter adapter = new OleDbDataAdapter();
connection.ConnectionString = connectionString;
if (connection.State != ConnectionState.Open)
connection.Open();
//connection.Get
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
connection.Open() seems to be connecting just fine. Now I have gotten a dtSchema Data Table object. I am needing to get the name of the Excel worksheet or worksheets that were gotten if any. I am also scanning the object to find out where the column names are. There is supposed to be some columns in the schema. Is it documented where the columns are?
When I do some output in my immediate window:
dtSchema.Columns[0].ToString()
"TABLE_CATALOG"
dtSchema.Columns[1].ToString()
"TABLE_SCHEMA"
dtSchema.Columns[2].ToString()
"TABLE_NAME"
dtSchema.Columns[3].ToString()
"TABLE_TYPE"
These are not the column names of the first worksheet, which is what I am looking for mainly the name of the first worksheet and its columns.
Thank you for posting..
If you want to look for column names. See the resultant COLUMN_NAME column
DataTable dtCols = this.connection.GetSchema("Columns");
TABLE_NAME is also helpful for your case to identify the Sheet.

Error in uploading excel file to database

I am working on a webform which has a file upload and a button and a gridview. user can upload excel file to database and also see preview in gridview .It is workin fine.
my code is
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Publisher/ExcelFiles/") + filename);
DataSet ds = new DataSet();
string path = #"~/Publisher/ExcelFiles/" + filename;
OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand myComm = new OleDbCommand("select * from [GIRLS$] ", myCon);
OleDbDataAdapter da = new OleDbDataAdapter(myComm);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
but my problem is path of excel file it gives me an error at da.Fill(ds);
'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Publisher\ExcelFiles\glist.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
excel file resides in my website directory. This error don't come if I changed the path to
string path= #"D:\Vikas Rana\New folder (4)\glist.xls";
any help will be appreciated.
Thanks in advance.
try this
string filename = Path.GetFileName(FileUpload1.FileName);
DataSet ds = new DataSet();
string path = Server.MapPath("~/Publisher/ExcelFiles/" + filename);
FileUpload1.SaveAs(path);
OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
DataSource=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand myComm = new OleDbCommand("select * from [GIRLS$] ", myCon);
OleDbDataAdapter da = new OleDbDataAdapter(myComm);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
if you upload .xls file use this
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path(which you prefer);Extended Properties="Excel 8.0;HDR=YES;IMEX=1;"
if you upload .xlsx file use this
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=path(which you prefer);Extended Properties="Excel 12.0;HDR=YES;IMEX=1;"
I mean
OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;
DataSource=" + path + ";Extended Properties=Excel 8.0;HDR=YES;IMEX=1;");

Error message "external table is not in the expected format" when I tried to upload file in C# program

I am creating a C# program where I can browse and view the file into a datagridview in C#. I've been tested it for so many times and it worked well. But yesterday when I tried to do it again an error messaged displayed stating "Provider=Microsoft.Jet.OLEDB.4.0;". The file that I am testing is the same file that I used before(with no errors). I didn't do anything with the file(excel file).
This is the print screen of the error message:
This is the code I used:
private void buttonUpload_Click(object sender, EventArgs e)
{
string OleDBConnection = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, OleDBConnection);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
If Path.GetExtension(pth).ToLower().Equals(".xls") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;"""
End If

Error when getting records from xlsx file in C#

I am getting an error when I attempt to read the records from my xlsx file.
The error is "Cannot update. Database or object is read-only."
I have verified that the file is not read-only. Any ideas what could be causing the error?
My code is:
string strFileName = System.IO.Path.GetFileName(txtSourcePath.Text);
string strFilePath = txtSourcePath.Text;
string strDirectoryPath = strFilePath.Substring(0, (txtSourcePath.TextLength - (strFileName.Length + 1)));
string conn = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""text;HDR=YES;FMT=DELIMITED""", strDirectoryPath);
OleDbConnection oleDBConn = new OleDbConnection(conn);
oleDBConn.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * FROM [" + strFileName + "]", conn);
DataSet ds = new DataSet();
da.Fill(ds);
When I hover over ds I don't see any records
Try This
for xls
<add key="xlsConnection" value="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=##PATH##;Extended Properties='Excel 8.0;HDR=YES;IMEX=1'"/>
for xlsx
<add key="xlsxConnection" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=##PATH##;Extended Properties='Excel 12.0;HDR=YES;'"/>
Required to install : microsoft.ace.oledb.12.0 driver
Replace Path of your excel file path

Categories