SIGN UP MEMBER LOGIN:    
ARTICLE

How to Convert Excel Data to a Table in SQL Server 2005

Posted by Sudhir Kumar Articles | SQL Server 2012 February 28, 2011
This article is about converting Excel data to a table. In this example I am using Ms SQL Server 2005 as the database. You can use any database by changing the connection string.
Reader Level:
Download Files:
 


This article is about converting Excel data to a table. In this example I am using Ms SQL Server 2005 as the database. You can use any database by changing the connection string.

1. First of all we have an Excel file. In the Excel file the first row should contain the field names. If the Excel file contains blank rows in the top, then the field names will be Filed1, Field2,Field3…and so on. For example the following shows the Excel data. Save this file and then use it.

Client Id

Client Name

Client Address

Amount

101

ABC Infotech

New York

100000

102

XYZ Systems

Manhattan

200000


2. Sometimes your column name may contain spaces. So in this example I am converting the blank space to underscore (_). Because in the database we cannot have a field name with a blank space.

3. First load the Excel file by giving a file dialog box.

excel.gif

using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
public void Browse_Click(object sender, EventArgs e)
{
             
Excel.Application ExApp;
      AllSheets.Items.Clear();
      FileTextBox.Text = "";
      try
      {
            openFileDialog1.Filter = "Excel Files (*.xls)|*.xls|All Files(*.*)|*.*";
            openFileDialog1.InitialDirectory = @"c:\";
            openFileDialog1.FileName = "Select File";
            openFileDialog1.Title = "Select excel file..";
            openFileDialog1.ShowDialog();
            ExcelFile = openFileDialog1.FileName; ;
            FileTextBox.Text = ExcelFile;
            ExApp = new Microsoft.Office.Interop.Excel.Application();

Excel.Workbook MyWorkbook = ExApp.Workbooks.Open(ExcelFile, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

            TotalSheets = MyWorkbook.Worksheets.Count;
            foreach (Excel.Worksheet wksh  in MyWorkbook.Worksheets)
            {
                    AllSheets.Items.Add(wksh.Name);
            }
            MyWorkbook.Close(false, false, false);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

}
Note: Because you are using the Excel properties, first add the reference for Excel.

4. When you will click on the Browse button it will ask for filename. Select the file and then whatever the sheets in that workbook will be displayed in ComboBox. Select any sheet and click on save.

Public void Save_Click()
{
             
OleDbConnection con = null;
      OleDbCommand com = null;
      OleDbDataAdapter da = null;
      DataSet ds = null;
string SheetName;

      SheetName = comboBox1.SelectedItem.ToString();

string constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFile + ";Extended Properties=Excel 8.0";
      con = new OleDbConnection(constr);
      con.Open();
      string strr = "select * from [" + SheetName + "$]";
      com = new OleDbCommand(strr, con);
      da = new OleDbDataAdapter();
      da.SelectCommand = com;
      ds = new DataSet();
      da.Fill(ds);
      TotalCols = ds.Tables[0].Columns.Count;
      TotalRows = ds.Tables[0].Rows.Count;

      string query=null;
      try
      {
SqlConnection con = new SqlConnection("Data Source=MyDataServer;Database=CustomerData;Integrated
Security=true"
);
            con.Open();
            SqlCommand com = new SqlCommand();
            com.Connection = con;
query = "create table Customer(" + ds.Tables[0].Columns[0].ToString().Replace(" ","_") + " varchar(200)";
            int i;
            for (i = 1; i < TotalCols; i++)
            {
                  string ActualField = ds.Tables[0].Columns[i].ToString();
                  string FinalField = ActualField.Replace(" ", "_");
                  query += "," + FinalField + " varchar(200)";
            }
            query += ")";
            com.CommandText = query;
            com.ExecuteNonQuery();
            int ins, co;
            query = "";
            for (ins = 0; ins < TotalRows; ins++)
            {
query = "insert into Customer values('" + ds.Tables[0].Rows[ins][0];
      for (co = 1; co < TotalCols; co++)
                  {
query += "','"+ds.Tables[0].Rows[ins][co].ToString();
                  }
                  query += "')";
                  com.CommandText = query;
                  com.ExecuteNonQuery();
            }
            MessageBox.Show("Record saved");
      }
      catch (Exception ex)
      {
            MessageBox.Show("error: "+query+ "--"+ex.Message);
      }
}

Login to add your contents and source code to this article
Article Extensions
Contents added by ramnaresh niranjan on Jan 05, 2012
share this article :
post comment
 

Hi.. I seen ur artical nice .. its very use-full for my project but. i need some suggestion when i add Excel libraries i not getting intellsense of Allsheets, AllRows , & I need to have only insert option in the save button because i wrote create table query in sql server 2008 pls check it

Posted by srikanth kumar Dec 13, 2011
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor