?
Solved

import excel to sql

Posted on 2007-11-15
5
Medium Priority
?
2,703 Views
Last Modified: 2013-12-17
I am trying to insert records into an existing sql table from an excel file in c# asp.net.  I would like to only insert specifi columns (both from the excel table and to the sql table) and specific rows (from the excel file).  All the help I could find was
insert into <sql> select * from <excel>

The error I receive is error in the INSERT INTO statement, but no details on what is failing.  See attached code.
if (FileUpload1.FileName == "")
                return;
 
            FileUpload1.SaveAs("c:\\EmployeeExpenses.xls");
 
            SqlConnection SQLConn = new SqlConnection("Data Source=KSSQL01;Initial Catalog=stamp;Integrated Security=SSPI");
            SQLConn.Open();
            SqlCommand SQLCommand = new SqlCommand("Delete tempEmployeeExpenses", SQLConn);
            SQLCommand.ExecuteNonQuery();
            SQLConn.Close();
 
            OleDbConnection ExcelConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\EmployeeExpenses.xls;Extended Properties=Excel 8.0;");
            ExcelConnection.Open();
            OleDbCommand ExcelCommand = new OleDbCommand(
                "INSERT INTO [ODBC;Driver={SQL Server};Server=KSSQL01;Database=stamp;Trusted_ Connection=yes].[tempEmployeeExpenses] "+
                "(Date, Description, CardMember, Amount) "+
                "SELECT [Date], [Description], [CardMember], [Amount] "+
                "FROM [Sheet1$] "+
                "WHERE [Sheet1$].[CardMember] = \"" + CardHolderName + "\";", ExcelConnection);
                
            ExcelCommand.ExecuteNonQuery();
            ExcelConnection.Close();

Open in new window

0
Comment
Question by:KS_Mis
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 18

Accepted Solution

by:
vbturbo earned 500 total points
ID: 20291036
well this reads an entire sheet into a dataset and the inserts the table into a sql database

public class Form1 {
   
    // Variables set for the form
    private OpenFileDialog dlgFile;
   
    private string filePath;
   
    private string fileNameNoPath;
   
    private string connectionString;
   
    private string fileNameNoExt;
   
    private DataRow dr;
   
    // Excel connection
    private OleDb.OleDbConnection ExcelConn;
   
    // Connection
    // SQL Server connection
    private OleDb.OleDbConnection SQLConn;
   
    // Connection var
    private string theSQLConnection = "Data Source=MONICASONY;Initial Catalog=dtc;Integrated Security=True;Provider=SQLOLEDB";
   
    private OleDb.OleDbDataAdapter SQLadapter = new OleDb.OleDbDataAdapter();
   
    // Adapter
    private OleDb.OleDbCommandBuilder SQLcommander;
   
    // Command Builder
    private System.Data.DataSet DtInstitution;
   
    // DataSet
    private OleDb.OleDbDataAdapter InstitutionCommand;
   
    // Adapter
    private void Button1_Click(object sender, System.EventArgs e) {
        int tmp;
        OpenFileDialog1.ShowDialog();
        filePath = OpenFileDialog1.FileName;
        fileNameNoPath = System.IO.Path.GetFileName(filePath);
        tmp = fileNameNoPath.IndexOf(".");
        fileNameNoExt = ("["
                    + (fileNameNoPath.Substring(0, tmp) + "$]"));
        connectionString = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                    + (filePath + ";Extended Properties=Excel 8.0;"));
        loadData(connectionString);
    }
   
    void loadData(string connection) {
        OleDb.OleDbConnection myConnection;
        System.Data.DataSet DtSetBreakOutAdvisor;
        System.Data.OleDb.OleDbDataAdapter myCommand;
        myConnection = new OleDb.OleDbConnection(connection);
        myCommand = new OleDb.OleDbDataAdapter(("select * from " + fileNameNoExt), connectionString);
        // myCommand.TableMappings.Add("Table", "Advisors")
        DtSetBreakOutAdvisor = new System.Data.DataSet();
        myCommand.Fill(DtSetBreakOutAdvisor);
        SQLConn = new OleDb.OleDbConnection(theSQLConnection);
        foreach (dr in DtSetBreakOutAdvisor.Tables[0].Rows) {
            dr.SetAdded();
        }
        try {
            SQLadapter.SelectCommand = new OleDb.OleDbCommand("select * from tempBreakout;", SQLConn);
            SQLcommander = new OleDb.OleDbCommandBuilder(SQLadapter);
            SQLadapter.FillSchema(DtSetBreakOutAdvisor, SchemaType.Mapped);
            SQLadapter.Update(DtSetBreakOutAdvisor.Tables[0]);
            DtSetBreakOutAdvisor.AcceptChanges();
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
        DataGridView1.DataSource = DtSetBreakOutAdvisor.Tables[0];
        myConnection.Close();
    }
   
    private void CloseToolStripMenuItem_Click(object sender, System.EventArgs e) {
        this.Close();
    }
}

vbturbo
0
 
LVL 18

Expert Comment

by:vbturbo
ID: 20291047
0
 

Author Comment

by:KS_Mis
ID: 20291710
that inserts all the columns, right?  What if I just want to insert a subset of columns?  Also the link was broken.
0
 
LVL 18

Expert Comment

by:vbturbo
ID: 20291811
sorry about the link

http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_22531755.html

this assumes that sheet columns are identical as within the sql table
of course you can manipulate the datatable object in the dataset as you like (e.g, ad , remove aggregate, rename...ect....) columns
as you like as long the number of columns and datatypes match

vbturbo
0
 
LVL 3

Expert Comment

by:Aurora27
ID: 20294864
* Its best to have a separate connection object.
* Next is..AFAIK, Insert goes like this: INSERT INTO tablename (field1, field2) VALUES ("123", "567");

Wheher its is a subset or u want to fill in the entire table, it shud be a similar format. Check it out. Why dont u split the statement and see where its failing..the code does not follow the best practices..having too many expressions to be evalauted in a single statement is not good..

My two cents.

Charu.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Suggested Courses

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question