Solved

load a db table from excel

Posted on 2006-10-23
7
207 Views
Last Modified: 2010-04-16
I am new to .net and i wanted to know how to implemnet thisi project that i have  been given and wanted an experts advice on the best way to implement the project.Plz advice.

Requiremnets:

Read from multiple sheets of an excel file  and load the single sql db table with this data from the excel file and also run a stored procedure in the background
to manupilate other db tables using this table.
This is an windows application.
Thank you.
0
Comment
Question by:pgupta81
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17793627
If its a one time requirement u can directly import data from excel into sql table using DTS.
In EM , rt click DATABSE, all tasks - Import and there u give source and destination, Ur source will be excel file
0
 
LVL 5

Expert Comment

by:rameedev
ID: 17793709
IF it is not a One time requirement then

On some Button Click Event (Or whatever is the UI event)...You could probably do something like this


Function LoadDataFrom ExcelAndUpdateDB()
{
    // Write your Code for filling some dataset from the Excel file
    // This Could return a DataSet
   
    foreach(DataRow dr in DataSet.Tables[0].Rows)
    {
        //Write your Code to take all the rows from the datatable and call your SP
    }
}


0
 

Author Comment

by:pgupta81
ID: 17794078
I have to develop a windows application on this thats why i cannot use EM DTS to do this..

How to iterate through multiple sheets of excel to load sql table?
Do i need to follow certain naming convention ?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Accepted Solution

by:
redpipe earned 125 total points
ID: 17794194
The following function takes a complete filepath to an Excel file and returns all sheetnames in the file as an string array.

public string[] GetSheetNames(string FilePath)
    {
      string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                          "Data Source=" + FilePath + ";" +
                          "Extended Properties=\"Excel 8.0;HDR=YES\"";
      OleDbConnection conn = null;
      string[] xlsSheets = null;
      DataTable dt = null;
      try {
        using (conn = new OleDbConnection(connString)) {
          if (conn.State != ConnectionState.Open) { conn.Open(); }
          dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
          if ((dt != null) || (dt.Rows.Count > 0)) {
            xlsSheets = new String[dt.Rows.Count];
            int i = 0;
            string sheetName;
            foreach (DataRow row in dt.Rows) {
              sheetName = row["TABLE_NAME"].ToString();
              if (sheetName.StartsWith("'")) { sheetName = sheetName.Remove(0, 1); }
              if (sheetName.EndsWith("'")) { sheetName = sheetName.Remove(sheetName.Length - 1, 1); }
              if (sheetName.EndsWith("$")) { sheetName = sheetName.Remove(sheetName.Length - 1, 1); }
              xlsSheets[i] = sheetName;
              i++;
            }
          }
        }
      } finally {
        if (conn != null) {
          try {
            conn.Close();
            conn.Dispose();
            conn = null;
          } catch (OleDbException exOleDb) {
            Logger.LogException(exOleDb);
          }
        }

        if (dt != null) {
          dt.Dispose();
        }
      }
      return xlsSheets;
    }
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17794198
Dim DS As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim MyConnection As System.Data.OleDb.OleDbConnection

MyConnection = New System.Data.OleDb.OleDbConnection( _
      "provider=Microsoft.Jet.OLEDB.4.0; " & _
      "data source=C:\myData.XLS; " & _
      "Extended Properties=Excel 8.0;")
' Select the data from Sheet1 of the workbook.
MyCommand = New System.Data.OleDb.OleDbDataAdapter( _
      "select * from [Sheet1$]", MyConnection)

DS = New System.Data.DataSet()
MyCommand.Fill(DS)
MyConnection.Close()
0
 
LVL 8

Expert Comment

by:redpipe
ID: 17794202
Forgot to submit the function for retrieving data from a given sheet.

public DataTable GetData(string FilePath, string SheetName, bool FirstRowIsHeader)
{
      string connString = null;
      if (FirstRowIsHeader) {
        connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                     "Data Source=" + FilePath + ";" +
                     "Extended Properties=\"Excel 8.0;HDR=YES\"";
      } else {
        connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + FilePath + ";" +
                    "Extended Properties=\"Excel 8.0;HDR=NO\"";
      }
      OleDbConnection conn = null;
      OleDbCommand cmd = new OleDbCommand();
      DataTable dt = null;
      IDataReader dr = null;
      try {
        using (conn = new OleDbConnection(connString)) {
          if (conn.State != ConnectionState.Open) { conn.Open(); }
          cmd.Connection = conn;
          cmd.CommandText = "SELECT * FROM [" + SheetName + "$]";
          OleDbDataAdapter adapter = new OleDbDataAdapter();
          adapter.SelectCommand = cmd;
          dt = new DataTable(SheetName);
          adapter.FillSchema(dt, SchemaType.Source);
          adapter.Fill(dt);
        }
      } finally {
        if (cmd != null) {
        cmd.Dispose();
        cmd = null;
      }

      if (dr != null) {
        dr.Close();
        dr.Dispose();
        dr = null;
      }

      if (conn != null) {
        try {
          conn.Close();
          conn.Dispose();
          conn = null;
        } catch (OleDbException exOleDb) {
          Logger.LogException(exOleDb);
        }
      }
      }
      return dt;
    }
0
 

Author Comment

by:pgupta81
ID: 17891855
code Helped!! Thanks
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Get String split 5 46
Create XML 5 46
Programmatically signing Word macros 4 61
System.Speech 2 9
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

914 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

21 Experts available now in Live!

Get 1:1 Help Now