Solved

import excel to sql

Posted on 2007-11-15
5
2,666 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
  • 3
5 Comments
 
LVL 18

Accepted Solution

by:
vbturbo earned 125 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
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…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

743 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now