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);
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();
}
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.
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);
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"