Error in uploading excel file to database - c#

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;");

Related

.Dat file to dataset

I have a .dat file that I need to import into a datatable. I am using .net framework 4.5 and it delimited by ~. How do I import this? I tried
string mySelectQuery = "SELECT * FROM " + fileName;
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileLocation + ";Extended Properties=\"text;HDR=YES;FMT=Delimited\"");
OleDbDataAdapter dsCmd = new OleDbDataAdapter(mySelectQuery, myConnection);
//Fill the DataSet object
dsCmd.Fill(myData, "Packets");
Please help

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

OleDBException when reading an open excel file

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;

Missing rows reading generated Excel file

I am creating an Excel File using OleDB, it works perfectly, next, I add rows to the file using directly in Office Excel , after, when i try read the file using OleDB again, the rows i added manually does not appear, only the columns and rows i wrote when i created the file.
Here is the code:
//Creation of the file
String connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + path + "; Mode=ReadWrite; Extended Properties= 'Excel 8.0; HDR=Yes; IMEX=0'";
OleDbConnection oledbconnection;
oledbconnection = new OleDbConnection(connectionString);
oledbconnection.Open();
String query = "CREATE TABLE [Sheet1] (....) ";
OleDbCommand cmd = new OleDbCommand(query, oledbconnection);
cmd.ExecuteNonQuery();
oledbconnection.Close();
it works perfectly, the file is created correctly, then, when im trying read the file after modify it, I'm doing this
String connectionStringRead = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + path + "; Extended Properties= 'Excel 8.0; HDR=Yes; IMEX=1'";
OleDbConnection oledbconnection;
oledbconnection = new OleDbConnection(connectionStringRead);
oledbconnection.Open();
DataTable table = new DataTable();
String sheetName;
sheetName = oledbconnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", oledbconnection);
adapter.Fill(table);
oledbconnection.Close();
return table;
The table contains ONLY the original information, not the rows I added using MS Excel.
I don't understand this, can you help me please ?
thanks in advance
Never try like that before, but if
sheetName = "Sheet1" '-------> or whatever
It should be
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "$]", oledbconnection);

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