COM Interop Exception when trying to read Excel file ASP.net - asp.net

I have a very simple ASP.net 4.0 application that lets users read data from a common Excel file. The Excel file is situated within the application itself i.e. it rests on the server side in a folder right below the root.
I'm populating a Dataset with the Excel data using this code:
public DataTable GetExcelData(string ExcelFilePath)
{
DataTable dt = new DataTable();
string OledbConnectionString = string.Empty;
OleDbConnection objConn = null;
OledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(OledbConnectionString);
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
string resName = "'";
string depName = department;
resName += userLastName + ", " + userFirstName + "'";
OleDbCommand objCmdSelect = new OleDbCommand("Select * from [" + depName + "$A3:Q10000] where Resource=" + resName, objConn);
OleDbDataAdapter objAdapter = new OleDbDataAdapter();
objAdapter.SelectCommand = objCmdSelect;
DataSet objDataset = new DataSet();
objAdapter.Fill(objDataset, "ExcelDataTable");
dt = objDataset.Tables[0];
addSumRow(dt);
objConn.Close();
return objDataset.Tables[0];
}
and after this I attache the Dataset to a Gridview and that's about it.
Now when I run the app on my local host there's no problem showing the Excel data, however, after deployment to our web server the application fails with this error:
The specified domain either does not exist or could not be contacted.
Description: An unhandled exception occurred during the execution of the current web >request. Please review the stack trace for more information about the error and where it >originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: The specified domain >either does not exist or could not be contacted.
Source Error:
An unhandled exception was generated during the execution of the current web request. >Information regarding the origin and location of the exception can be identified using >the exception stack trace below.
Any help is very much appreciated!
Thanks!

few thing you may try
1>Disable anonymous access and enable identity impersonation
2>Ensure Excel file path is correct

Related

'SqlConnection' is not declared error for aspx net

I am fairly new to this Aspx.Net. I am trying to connect to a remote SQL Server and below is the connection string I am trying on IIS server.
SQL Server version is 2012
MySqlConnection connection = new MySqlConnection("Database=DB;Server=server.name;Uid=user.name;Pwd=pass");
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "select * from dbo.TableName";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//reader.GetString(0)
//reader["column_name"].ToString()
}
reader.Close();
Below is the error:
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30451: Name 'SqlConnection' is not declared.
Appreciate any help, please keep in mind this is my first tries out on aspx. Yes, I tried searching online but can't seem to find a resolution.
Well, if you want to use SQL Server in C#, try follow below technique:
SqlConnection sqlConn = new SqlConnection("Server=server.name;Database=DB;User Id=userid;Password=yourpass;");
SqlCommand cmd = new SqlCommand("select * from dbo.TableName", sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//reader.GetString(0)
//reader["column_name"].ToString()
}
reader.Close();
sqlConn.Close();

How can i run Bulk insert from client file path in asp.net?

I want to write a web application for the client user to select a file from client system and
start uploading that file to server with bulk insert,i have written this query:
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/") + filename);
String paht = Server.MapPath("~/") + filename;
string bulkInsertQuery = "BULK INSERT Table_1 from '" + paht + "' WITH( FIELDTERMINATOR = ',',ROWTERMINATOR = '\n',CODEPAGE = '1256'); ";
using (SqlConnection con = new SqlConnection(connection))
{
using (SqlCommand cmd = new SqlCommand(bulkInsertQuery, con))
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}//end of using
}//end using 1
But when run that code,i get this error:
{"Bulk load: An unexpected end of file was encountered in the data file.\r\nThe OLE DB provider \"BULK\" for linked server \"(null)\" reported an error. The provider did not give any information about the error.\r\nCannot fetch a row from OLE DB provider \"BULK\" for linked server \"(null)\"."}
what is happening ?how can i solve this?thanks.

Getting unspecified error while Reading CSV file using OleDbDataAdapter

Update 1 : I think schema.ini is incorrect. Please refer to below question.
The file (dsTextFile) has just one row of data but record count is zero. So it means it is not reading at all. This is with removing FMT altogether or with Delimi. I still get error if FMT is fixed though. So, how do I create SCHEMA.ini or make sure schema.ini is correct?
private bool LoadTextFile(string textFilePath, out string errorInfo) {
errorInfo = String.Empty;
try {
string textFileFolder = (new System.IO.FileInfo(textFilePath)).DirectoryName;
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Fixed\";";
OleDbConnection textConnection = new OleDbConnection(textConnectionString);
textConnection.Open();
textFilePath = (new System.IO.FileInfo(textFilePath)).Name;
string selectCommand = "select * from " + textFilePath;
OleDbCommand textOpenCommand = new OleDbCommand(selectCommand);
textOpenCommand.Connection = textConnection;
OleDbDataAdapter textDataAdapter = new OleDbDataAdapter(textOpenCommand);
Console.WriteLine("Trying to set textDataAdapter");
int rows = textDataAdapter.Fill(dsTextFile); //This is where error is coming.
Console.WriteLine("detail rows being filled");
textConnection.Close();
textConnection.Dispose();
return true;
}
catch (Exception ex_load_text_file) {
Console.WriteLine("error in loadTextFile is " + ex_load_text_file.Message.ToString());
return false;
}
}
Please find the above source where I am getting error 'UnSpecified" for below line.
UnSpecified Error is coming at below line
int rows = textDataAdapter.Fill(dsTextFile)
What could be the issue? I have checked user permissions on c:\windows\temp but no success.
This is a console application and I have even tried to add below code in app.config but no success yet.
<system.web>
<identity imperonate = "false"/> </system.web>
This is a legacy application but needs to run on windows server 2012 setup.
You are using FMT=Fixed on the connection string, if you are not using a schema.ini, change it to FMT=Delimited and it will work.
i.e.:
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Delimited\";";

The Microsoft Jet database engine could not find the object 'Sheet1$'

I'm attempting to read a spreadsheet file called Book1.xls which contains a worksheet called Sheet1
However I'm getting the following error:
The Microsoft Jet database engine could not find the object 'Sheet1$'.
Make sure the object exists and that you spell its name and the path
name correctly.
Here is a snippet of the code I'm using:
Dim dt As DataTable = New DataTable()
Select Case fileExt
Case ".csv"
Dim reader As New CsvReader
dt = reader.GetDataTable(filePath)
Case ".xls", ".xlsx"
Dim oleDbConnStr As String
Select Case fileExt
Case ".xls"
oleDbConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
Case ".xlsx"
oleDbConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
End Select
Using oleDbConn As OleDbConnection = New OleDbConnection(oleDbConnStr)
oleDbConn.Open()
Dim oleDbCmd As New OleDbCommand("SELECT * FROM [Sheet1$]", oleDbConn)
Dim oleDbDa As New OleDbDataAdapter(oleDbCmd)
oleDbDa.Fill(dt)
oleDbConn.Close()
End Using
End Select
I can't understand why the code cannot find my worksheet. Why is this, and how can I resolve it?
I've found the problem.
It seems the spreadsheet was being saved to the wrong location, so filepath wasn't pointed to a file which exists.
I didn't check this at first because I assumed a different error message would appear. Something like "Book1.xls could not be found". However it seems like if it doesn't exist, then the message will just state that it cannot find the Worksheet.
If file name has additional dot character like below:
sample.data.csv
next select statement:
SELECT * FROM [sample.data.csv]
with connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Data\"; Extended Properties="text;HDR=Yes;Format=Delimited;";
will fail with exception:
Additional information: The Microsoft Jet database engine could not find the object 'sample.data.csv'. Make sure the object exists and that you spell its name and the path name correctly.
Also - make sure you don't have the file open in Excel already. You won't be able to read the file if it's open somewhere else. I had the same error and realized I had the file open in Excel.
Not sure, I have some similar code (C#) that works well...
Maybe you can spot a difference?
string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'", excelFilePath);
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = #"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]";
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
.......
}
}
}
connection.Close();
}
}
Try renaming your sheet; or explicitly adding columns; or checking if it's case sensitive.
Change your Excel file location, this error will be resolved.
may put your file in the same folder where your source present
best solution through vb coded from this link, all credits to these folks-
http://www.vbforums.com/showthread.php?507099-data-from-excel-sheet-to-datagrid-(vb)
C# My expected solution below
string connString = "Driver={Microsoft Excel Driver (*.xls)};READONLY=FALSE;DriverId=790;Dbq=" + "C:\\Users\\BHARAVI\\Documents\\visual studio 2013\\Projects\\ERP\\ERPAutomation\\Assets\\Data\\Data.xls";
OdbcConnection conn = new OdbcConnection(connString);
conn.ConnectionTimeout = 500;
OdbcCommand CMD = new OdbcCommand("SELECT * FROM [Sheet1$]", conn);
OdbcDataAdapter myDataAdaptor = new OdbcDataAdapter(CMD);
DataSet ds = new DataSet();
myDataAdaptor.Fill(ds ,"Sheet1");
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
loginId = dr["LoginId"].ToString();
encryptedPassword = dr["PWD"].ToString();
URL = dr["URL"].ToString();
}

Cannot delete excel file after importing data from it using OleDB, says it is being used by another process

I'm importing data from an Excel file in ASP.NET using OleDB. After finishing the import, I want to delete the file using the command System.IO.File.Delete(), but it throws the following exception:
The process cannot access the file '...29.xls' because it is being used by another process.
I used the following code to open and close the file:
Dim fajl As String
fajl = MapPath("fajlovi/" + Request.QueryString("ID"))
Dim sConnectionStringExcel As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fajl & ";Extended Properties=Excel 8.0;"
Dim objConnExcel As New OleDbConnection(sConnectionStringExcel)
objConnExcel.Open()
Dim objCmdSelectExcel As New OleDbCommand("SELECT ZavedenKodPov, Ime, Mjesto, Adresa, JMBG, LicniBroj, ZaposlenKod, Nepoznat, Umro, Penzioner, Reon, VoziloProizvodjac, VoziloModel, VoziloRegistracija, Nekretnina, Datum, KontoBroj, NazivKonta, OpisPromjene, Dug, Pot FROM [Sheet1$]", objConnExcel)
Dim objAdapterExcel As New OleDbDataAdapter()
objAdapterExcel.SelectCommand = objCmdSelectExcel
Dim objDatasetExcel As New DataSet()
objAdapterExcel.Fill(objDatasetExcel, "XLData")
Dim tExcel As DataTable
tExcel = objDatasetExcel.Tables(0)
'.
'.
'.
objConnExcel.Close()
System.IO.File.Delete(fajl)
Any ideas what I'm doing wrong?
dispose of the command and connection, preferably wrapped in a using statement. then you should be able to delete the file.

Resources