I am trying to create program in .net using C# for uploading excel file, reading it and add record excel file to the sql server database from excel data.
While doing so I have got an error: Could not find installable ISAM?
Can someone help me how to fix this problem?
Or may be provide some sample code to do such kind of assignment in different way?
protected void Button1_Click(object sender, EventArgs e)
{
String excelConnectionString1;
String fname = FileUpload1.PostedFile.FileName;
if (FileUpload1.PostedFile.FileName.EndsWith(".xls"))
{
String excelsheet;
FileUpload1.SaveAs(Server.MapPath("~/file/" + FileUpload1.FileName));
if (FileUpload1.PostedFile.FileName.EndsWith(".xls"))
{
excelConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/file/" + FileUpload1.FileName) + ";Extended Properties=Excel 8.0;HDR=Yes;";
OleDbConnection myEcelConnection1 = new OleDbConnection(excelConnectionString1);
myEcelConnection1.Open();
if (txtsheet.Text.Length == 0)
{
lblmsg.Text = "Please Write File Name";
}
else
{
excelsheet = "[" + txtsheet.Text + "$" + "]";
string sheet = "Select * from [" + txtsheet.Text + "$" + "]";
OleDbCommand cmd1 = new OleDbCommand(sheet, myEcelConnection1);
cmd1.CommandType = CommandType.Text;
OleDbDataAdapter myAdapter1 = new OleDbDataAdapter(cmd1);
DataSet myDataSet1 = new DataSet();
myAdapter1.Fill(myDataSet1);
int a = myDataSet1.Tables[0].Rows.Count - 1;
string name;
string dob;
for (int i = 0; i <= a; i++)
{
name = myDataSet1.Tables[0].Rows[i].ItemArray[0].ToString();
dob = myDataSet1.Tables[0].Rows[i].ItemArray[1].ToString();
SqlConnection con = new SqlConnection("Connection String for Sql Server");
con.Open();
SqlCommand command = new SqlCommand("Insert into info(name,dob)values(#valname,#valdob)", con);
command.Parameters.Add("#valname", SqlDbType.VarChar, 50).Value = name;
command.Parameters.Add("#valdob", SqlDbType.VarChar, 50).Value = dob;
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
}
}
}
}
}
}
There's no 64 bit version of the Jet OLEDB drivers, so if you are running this on a 64 bit OS you might need to target x86 in your .NET application and not Any CPU.
Or
This error will also be generated when the syntax of the connection string is incorrect. This commonly occurs when using multiple Extended Properties parameters. Below is an example:
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=e:\My Documents\Book20.xls;Extended Properties=""Excel 12.0;HDR=NO;IMEX=1"""
Change connection string like this
ConnectionString=" Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\NAVEEN KUMAR\DOTNET\windows\WindowsApplication1\WindowsApplication1\123.xls;Excel 12.0 Xml;HDR=YES"
Related
I Want to skip a few rows in an excel file, 15 rows(A1 to A14) to be able to import in sql server... But What I'm finding in internet doesn't work with me, I was thinking if you guys could take a look in my code
protected void Upload_Click(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
string filepath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.FileName);
string filename = Path.GetFileName(filepath);
FileUpload1.SaveAs(excelPath);
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 * from [rptListaMovs_4$]", excelConnection);
excelConnection.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from [rptListaMovs_4$] ", strConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
sqlBulk.DestinationTableName = "Dados";
sqlBulk.ColumnMappings.Add("Data Mov", "Data Mov.");
sqlBulk.ColumnMappings.Add("Data Valor", "Data Valor");
sqlBulk.ColumnMappings.Add("Descrição do Movimento", "Descrição do Movimento");
sqlBulk.ColumnMappings.Add("Valor em EUR", "Valor em EUR");
sqlBulk.WriteToServer(dReader);
}
excelConnection.Close();
}
I already tried put the "IEnumerable" but it didn't work, I probably did it wrong.
If you know you always want to skip exactly the first 14 rows and start your query importing at A15, then you can write your SQL query like this:
Select * from [rptListaMovs_4$A15:G]
Replace G with the correct column Letter
P.S. Credit to this answer for this inspiration.
#MacroMarc and ADyson Helped me
Here's the solution:
OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$A15:D75]", excelConnection);
Insted of This:
OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$]", excelConnection);
This is my code, I has put this function in my case there, why can I still not retrieve any data from my MS Access database? Is it the database problem? Or because my MS Access is version 2013 which is a pirated version?
public void display(event_detail e)
{
string path = Directory.GetCurrentDirectory();
string connstring = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + #"\GameMuseumManagementSystem.mdb";
OleDbConnection conn = new OleDbConnection(connstring); //Create connection
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * from Event WHERE Event_Title ='" + PassName + "'", conn); //Create command
cmd.Connection = conn; //command connect to database
OleDbDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
e.notxt.Text = (myReader["Event_No"].ToString());
//e.notxt.ReadOnly = true;
e.titletxt.Text = (myReader["Event_Name"].ToString());
//e.titletxt.ReadOnly = true;
e.datedetail.Text = (myReader["Event_Date"].ToString());
//e.datedetail.ReadOnly = true;
e.detailtxt.Text = (myReader["Event_detail"].ToString());
//e.detailtxt.ReadOnly = true;
}
}
Below is my code, any help will be greatly appreciated
:The Microsoft Office Access database engine could not find the object 'Breach'. Make sure the object exists and that you spell its name and the path name correctly.
public void importdatafromexcel(string excelfilepath)
{
string ssqltable = "Testing";
string myexceldataquery = "select [Case Owner],[Case Number],[Severity] from [Breach]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 12.0;";
string ssqlconnectionstring = "Persist Security Info=False;Integrated Security=true;Initial Catalog=0Breach;server= CHAUDAHARI-J1-W\\SQLEXPRESS";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
txtProcessingStatus.Text = ex.Message;
}
}
select [Case Owner],[Case Number],[Severity] from [Breach]
Is there a worksheet named "Breach" in the Excel file you are opening? In your statement above, I believe [Breach] should be the name of the worksheet you are looking for in the Excel file you are opening.
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();
}
}
Reword the question... the below code inserts the data into an SQL Server database, and into the correct table however, the data is not inserted correctly... here is the code
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DbDataReader dr = cmd.ExecuteReader();
string con_str = #"Data Source=ENERGYSQL\ENERGY;Initial Catalog=ProjectHandler;Persist Security Info=True;User ID=aconyon;Password=birchall";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName = "StockTable";
bulkInsert.WriteToServer(dr);
OleDbcon.Close();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
//Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
}
else
{
//Label1.ForeColor = ConsoleColor.Red;
Label1.Text = "please select ther File";
}
what this code does is select the far most right column, in my example Quantity, and insert just this into the database, ignoring all other rows (A and B) do i need to change the OleDbCommand to select certain rows. A(ItemName), B(Date), C(Quantity)
use this code.
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'",
Server.MapPath(#"~\DownloadedExcelFilesOp4\myfile" + fileExt));// + "\\" +
FileUploadControl.PostedFile.FileName.ToString());
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand(("Select [Demo1] ,[Demo2] FROM [Sheet1$]"),
connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
}
}
You can use query like below to get the value of any particular column.
OleDbCommand command = new OleDbCommand(("Select [Col1] ,[Col2] FROM [Sheet1$]"),
connection);