This code is working fine on localhost but when I try to run this code in server its not working..can anyone tell me what's wrong?
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.;Initial Catalog=EkkiDB;Integrated Security=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 [SurveyDate],[DealerName],[Model],[HP],[Quantity],[ID] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Import_Survey";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath( FileUpload fileUploadControl)
{
//string filePath = Server.MapPath(fileUploadControl.FileName);
// string filePath = Path.Combine(saveDirectory);
string filePath = Server.MapPath("~/xl/") + Path.GetFileName(fileUploadControl.PostedFile.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
Where is your destination directory? If it's not under IIS control check that your anonymous user account has write access to it.
Related
Well, I'm doing a program that imports data from an excel file into a database(sql server). The program runs fine if I save the excel file in IIS express folder but if I put in documents folder or something like it, it gives me an error:
here's the code:
protected void Upload_Click(object sender, EventArgs e)
{
string filepath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
String strConnection = #"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select [Name],[City],[Age] from [Sheet1$]", excelConnection);
excelConnection.Open();
//cmd.ExecuteNonQuery();
// DataSet ds = new DataSet();
// SqlDataAdapter da = new SqlDataAdapter("Select [Name],[City],[Age] from [sheet1$]", strConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Test";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
Try
string filepath = Server.MapPath(FileUpload1.FileName);
string filepath = Server.MapPath("~/Files/")Path.GetFileName(FileUpload1.FileName);
Cannot save my excel file in a folder that I create in my project... I think I forgot something while doing the especification of the path... Maybe I have to do something after?
I Already put the users with permissions and things like that, I THINK that the file isnt open I just have 1 user and nothing is open..
here's the code guys:
protected void Upload_Click(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string filepath = Server.MapPath("~/Files/");
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
String strConnection = #"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select [Name],[city],[age] from [Sheet1$]", excelConnection);
excelConnection.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select [Name],[city],[age] from [Sheet1$]", strConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Test";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
I have developed a functionality, where I import Excel sheet to the table. But when I upload the file and click on the button to import. The code doesn't works and gives me the below mentioned error. I tried with DataAdapter but that was also not working. Please see the error below:-
The Microsoft Office Access database engine could not find the object
'TableName'. Make sure the object exists and that you spell its
name and the path name correctly.
Also, Please see the code for your reference:-
private void ImporttoSQL(string sPath)
{
string sSourceConstr1 = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""", sPath);
string sSourceConstr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [MerchantTempDetail]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
conn.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.DestinationTableName = "MerchantTempDetail";
//You can mannualy set the column mapping by the following way.
// bulkCopy.ColumnMappings.Add("Mini_Category_Id", "Mini_Category_Id");
//bulkCopy.ColumnMappings.Add("CategoryId", "CategoryId");
bulkCopy.ColumnMappings.Add("Merchant_Name", "Merchant_Name");
bulkCopy.ColumnMappings.Add("Store_Name", "Store_Name");
bulkCopy.ColumnMappings.Add("Store_Address", "Store_Address");
bulkCopy.ColumnMappings.Add("City", "City");
bulkCopy.WriteToServer(dr);
}
}
}
}
Edited code :-
public static void ExcelToSqlServerBulkCopy()
{
// Connection String to Excel Workbook
// Jet4
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""";
// Ace Ole db 12
string excelAceOleDb12ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=AgentList.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelAceOleDb12ConnectionString))
{
OleDbCommand command = new OleDbCommand("Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [Sheet1$]", connection);
// open excel
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "MerchantTempDetail";
bulkCopy.WriteToServer(dr);
}
}
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string sPath = Server.MapPath(FileUpload1.FileName);
FileUpload1.SaveAs(sPath);
ExcelToSqlServerBulkCopy();
}
}
You need to define 2 connections, one for the Excel source, another for the sql database you are bulk copying to. (This code has been tested) If you need to copy to an in-memory data table, use this example on MSDN.
public static void ExcelToSqlServerBulkCopy ()
{
// Connection String to Excel Workbook
// Jet4
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""";
// Ace Ole db 12
string excelAceOleDb12ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=AgentList.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelAceOleDb12ConnectionString))
{
OleDbCommand command = new OleDbCommand("Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [AgentList$]", connection);
// open excel
connection.Open ();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader ())
{
// SQL Server Connection String
string sqlConnectionString = #"Data Source=.\SQLEXPRESS;Initial Catalog=StackOverflow;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy (sqlConnectionString))
{
bulkCopy.DestinationTableName = "Q26382169";
bulkCopy.WriteToServer (dr);
}
}
}
}
Very important details using variable names above:
the database you are copying to (StackOverflow) must be created a priori.
the destination table (Q26382169) must exist in that database, DDL trivial, same columns as your Excel file.
Since you are using HDR=YES option, first row of Excel sheet must contain specified column names: Merchant_Name, Store_Name, Store_Address, City (without [])
The name of the sheet in the OleDbCommand (AgentList$)
Finally solved by debugging it.
private void ImporttoSQL(string sPath)
{
string sSourceConstr1 = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""", sPath);
string sSourceConstr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
// string sSource = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sPath + ";Extended Properties=Excel 8.0", sPath);
// string sDestConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
string sql = "Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
conn.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.DestinationTableName = "MerchantTempDetail";
bulkCopy.ColumnMappings.Add("Merchant_Name", "Merchant_Name");
bulkCopy.ColumnMappings.Add("Store_Name", "Store_Name");
bulkCopy.ColumnMappings.Add("Store_Address", "Store_Address");
bulkCopy.ColumnMappings.Add("City", "City");
bulkCopy.WriteToServer(dr);
}
}
}
}
I want to import data from an Excel 2003 file, but my C# program gives error
External table is not in the expected format
I use this code:
string ExcelContentType = "application/vnd.ms-excel";
string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (fileuploadExcel.HasFile)
{
//Check the Content Type of the file
if (fileuploadExcel.PostedFile.ContentType == ExcelContentType || fileuploadExcel.PostedFile.ContentType == Excel2010ContentType)
{
try
{
//Save file path
string path = string.Concat(Server.MapPath("~/TempFiles/"), fileuploadExcel.FileName);
//Save File as Temp then you can delete it if you want
fileuploadExcel.SaveAs(path);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Excel_table";
bulkCopy.WriteToServer(dr);
lblMessage.Text = "The data has been exported succefuly from Excel to SQL";
}
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
}
Hi here i am using this to import from Excel File.Try this.Works 100%...
Here you should have a folder inside your application named as "Files" where after uploading your excel file,it will be stored and your program will read from the excel file available inside "Files" Folder.
protected void btnImport_Click(object sender, EventArgs e)
{
ArrayList alist = new ArrayList();
string connString = "";
string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
string fileBasePath = Server.MapPath("~/Files/");
string fileName = Path.GetFileName(this.fileuploadExcel.FileName);
string fullFilePath = fileBasePath + fileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
}
if (fileuploadExcel.HasFile)
{
string query = "SELECT [UserName],[Education],[Location] FROM [Sheet1$]";
using(OleDbConnection conn = new OleDbConnection(connString))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Session["griddata"] = ds.Tables[0];
grvExcelData.DataSource = Session["griddata"];
grvExcelData.DataBind();
}
}
}
Try this: Connection String
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
You can use SSIS tool( Sql server integration services)
create connection to excel sheet then add source and destination
your source will be excel sheet and your destination will be Database table
ok?
if you need more info please tell me...
the thing is that I need to select only 2 columns from the data in Excel, so i went on using sql for retrieving the data from the Excel file. But this time i keep getting "failed to create file" error and this happens when i try to open my connection. Why is it trying to create a file ?
my code:
public void ReadExcelFile()
{
string connectionString = string.Format(ConfigurationManager.ConnectionStrings["ExcelConnection"].ConnectionString.Replace("'", "\""), "#C:/Temp/Copy.xlsx");
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
string sqlCmd = "SELECT * FROM [Ark1$]";
using (OleDbCommand command = new OleDbCommand(sqlCmd, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.ToString());
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("ERROR in ReadExcelFile() method. Error Message : " + exception.Message);
}
}
}
can anyone help me with this ?
** EDITED **
Test it like this:-
string filename = "#C:\Temp\Copy.xlsx";
OleDbConnection con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filename + ";Extended Properties=\Excel 8.0;HDR=YES;IMEX=1\"");
To configure OleBConnection for read Excel file try this:
string filename = "#C:\Temp\Copy.xlsx";
OleDbConnection connection =new OleDbConnection(
"provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+filename+"';"+
"Extended Properties=Excel 8.0;");