Solved

import excel to sql

Posted on 2007-11-15
5
2,696 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 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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

707 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