[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

import excel to sql

Posted on 2007-11-15
5
Medium Priority
?
2,706 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

649 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