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...
Related
I have an Excel Upload in which there are columns for dates which while uploading is giving me error as
orA-01843: not a valid month while uploading excel in bulkCopy
Below is the code.
protected void btnUpload_Click(object sender, EventArgs e)
{
//Coneection String by default empty
string ConStr = "";
//Extantion of the file upload control saving into ext because
//there are two types of extation .xls and .xlsx of excel
string ext = Path.GetExtension(FileUploadIPFee.FileName).ToLower();
//getting the path of the file
string path = Server.MapPath("~/UploadData/" + FileUploadIPFee.FileName);
//saving the file inside the MyFolder of the server
FileUploadIPFee.SaveAs(path);
if (ext.Trim() == ".xls")
{
//connection string for that file which extantion is .xls
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (ext.Trim() == ".xlsx")
{
//connection string for that file which extantion is .xlsx
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//making query
string query = "SELECT * FROM [Sheet1$]";
//Providing connection
OleDbConnection conn = new OleDbConnection(ConStr);
//checking that connection state is closed or not if closed the
//open the connection
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//create command object
OleDbCommand cmd = new OleDbCommand(query, conn);
// create a data adapter and get the data into dataadapter
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
//DataSet ds = new DataSet();
DataTable dt = new DataTable();
//fill the excel data to data set
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
SaveUsingOracleBulkCopy("IPCOLO_IPFEE_CALC_MST", dt);
}
conn.Close();
// SaveUsingOracleBulkCopy("IPCOLO_IPFEE_CALC_MST", dtExcelRows);
}
public void SaveUsingOracleBulkCopy(string destTableName, DataTable dt)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString_IPCOLO"].ToString();
try
{
using (var connection = new Oracle.DataAccess.Client.OracleConnection(connectionString))
{
connection.Open();
using (var bulkCopy = new Oracle.DataAccess.Client.OracleBulkCopy(connection, Oracle.DataAccess.Client.OracleBulkCopyOptions.UseInternalTransaction))
{
bulkCopy.DestinationTableName = destTableName;
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.WriteToServer(dt); // here is the error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Data Uploaded Successfully')", true);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
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);
I am reading excel sheet using below code but that gives blank data table.
public static DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch(Exception ex) { }
}
return dtexcel;
}
It displays empty data table as below screenshot.
you forgot few things, like OleDbConnection.Open(); and using OleDbCommand
public DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string sheetName = "Sheet1$";
string conn = string.Empty;
DataTable dt = new DataTable();
if (fileExt.CompareTo(".xlsx") != 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
using ( OleDbCommand cmd = new OleDbCommand())
{
con.Open();
try
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
dt.TableName = sheetName;
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (Exception ex) { }
}
return dt;
}
try rhis code hope it help you
protected void btn_Click(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("File/" + filename));
string CurrentFilePath = Server.MapPath("File/" + filename);
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CurrentFilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
conn.Open();
DataTable Sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [" + sht + "]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
}
}
For me working following code
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "").Replace("\\bin\\Release", "");
string fileLocation = filePath + ConfigurationManager.AppSettings["EmployeeDetailsFilePath"];
Stream inputStream = File.Open(fileLocation, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(inputStream);
reader.IsFirstRowAsColumnNames = true;
DataSet dataSet = reader.AsDataSet();
inputStream.Dispose();
reader.Dispose();
here must add reference of ExcelDataReader dll in your project.
I want to import excel file data in to SQL Server but this gives an error as shown below:
external table is not in the expected format xls
I am working on windows 8.1 OS and excel 2013. I am using the following code.
try
{
if (FlUploadcsv.HasFile)
{
string FileName = FlUploadcsv.FileName;
string filePath = "C:\\Users\\admin\\Desktop\\Sheet1.xlsx";
string path = filePath;// string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
ds = new DataSet();
objAdapter1.Fill(ds);
Dt = ds.Tables[0];
}
}
catch (Exception ex)
{
}
First you need to Replace Connection string :
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
With this :
If you are use import for .xls then use below one :
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
If you are use import for .xlsx then use below one :
OleDbConnection OleDbcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
Try this blow one :
try
{
if (FlUploadcsv.HasFile)
{
OleDbConnection OleDbcon;
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dtExcelData = new DataTable();
string FileName = FlUploadcsv.FileName;
string filePath = "C:\\Users\\admin\\Desktop\\Sheet1.xlsx";
string path = filePath;// string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
if (Path.GetExtension(path) == ".xls")
{
OleDbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
OleDbcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbcon.Open();
cmd.Connection = OleDbcon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
objAdapter1 = new OleDbDataAdapter(cmd);
objAdapter1.Fill(ds);
dtExcelData = ds.Tables[0];
string consString = "Your Sql Connection string";
/* You want insert into your sql database table using SqlBulkCopy. */
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "SqlDatabase Table name where you want insert data";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add(".xls/.xlsx Header column name(Id)", "Your database table column(IndexId)");
.
.
.
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
/* You want insert into your sql database table using SqlBulkCopy. */
}
}
catch (Exception ex)
{ }
Here is a similar way to do it:
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
if (FileUpload1.HasFile == true) {
string fp = System.IO.Path.GetDirectoryName(FileUpload1.FileName);
string full = "C:\\Users\\user\\Documents\\" + filename;
TextBox1.Text = full;
//FileUpload1.SaveAs(Server.MapPath("Files/" + filename))
try {
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=full;Extended Properties=Excel 8.0;HDR=YES;";
string cmdStr = "Select * from [Sheet1$]";
using (OleDbConnection oledbconn = new OleDbConnection(connStr)) {
using (OleDbCommand oledbcmd = new OleDbCommand(cmdStr, oledbconn)) {
oledbconn.Open();
OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);
DataSet ds = new DataSet();
oledbda.Fill(ds);
//save to an SQL Database
oledbconn.Close();
}
}
} catch (Exception ex) {
TextBox2.Text = ex.ToString();
}
}
I am trying to find the best way of selecting an excel spreadsheet (xls and xlsx) using a fileupload control and then parsing it with filestream object and then populating a dataset.
This is my code so far which does the job but how it differs is I am saving the excel spreadsheet to a folder in my solution then querying the data using Microsoft ACE OLEDB connection.
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
//Path.GetExtension(ctrlFileUpload.PostedFile.ContentType);
string fileLocation =
Server.MapPath("~/App_Data/" + fileName);
ctrlFileUpload.SaveAs(fileLocation);
// Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
}
// Create OleDb Connection and OleD Command
using (OleDbConnection con = new OleDbConnection(connectingString))
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
//DataTable dtExcelRecords = new DataTable();
DataSet ds = new DataSet();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "Select * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
//dAdapter.Fill(dtExcelRecords);
dAdapter.Fill(ds);
//GridView1.DataSource = dtExcelRecords;
//GridView1.DataBind();
}
catch (Exception ex)
{
}
}
}
}
So to summarise I want to read the data in a spreadsheet and then bind it to a dataset but without saving the file to a physical path.
Is there a cleaner way of writing this code that I am missing. Thanks!!
I think it not possible to get data without save file to your server
If you can't save uploded file how can you give Data Source to your oleDbConnection string ??
you can delete file after finish this execution if you don't want to keep the file.
you can also refer this way https://stackoverflow.com/a/12420416/284240