ASP.NET - Import Excel sheet into database

Asked By Rajiv Sharma on 26-Jul-11 04:56 AM
hi,


Is it possible to import excel sheet into sql database

if so than please give me few examples

thanks
Ravi S replied to Rajiv Sharma on 26-Jul-11 05:01 AM
HI

Just a little bit of code transfers the data from the Excel Spreadsheet into the SQL Server Database Table:


// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft
.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended
Properties=""Excel 8.0;HDR=YES;""
"; // Create Connection to Excel Workbook using (OleDbConnection connection =
new OleDbConnection(excelConnectionString)) { OleDbCommand command = new OleDbCommand
(
"Select ID,Data FROM [Data$]", connection); connection.Open(); // Create DbDataReader to Data Worksheet using (DbDataReader dr = command.ExecuteReader()) { // SQL Server Connection String string sqlConnectionString = "Data Source=.;
Initial Catalog=Test;Integrated Security=True
"; // Bulk Copy to SQL Server using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName = "ExcelData"; bulkCopy.WriteToServer(dr); } } }



refer the links also
http://www.davidhayden.com/blog/dave/archive/2006/05/31/2976.aspx
http://www.4guysfromrolla.com/articles/022708-1.aspx#postadlink
Jitendra Faye replied to Rajiv Sharma on 26-Jul-11 05:01 AM

Using sqlBulk Class you can export excel file to DataBase.

Use this code-

protected void btnSend_Click(object sender, EventArgs e)
{
String strConnection = "Data Source=MySystem;Initial Catalog=MySamplesDB;Integrated Security=True";

//file upload path
string path = fileuploadExcel.PostedFile.FileName;

//Create connection string to Excel work book
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";

//Create Connection to Excel work book
OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]",excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}

Try this code and let me know.

Kalit Sikka replied to Rajiv Sharma on 26-Jul-11 05:02 AM

Using SqlBulkCopy to Import Excel Spreadsheet Data into SQL Server


// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft
.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended
Properties=""Excel 8.0;HDR=YES;""
"; // Create Connection to Excel Workbook using (OleDbConnection connection =
new OleDbConnection(excelConnectionString)) { OleDbCommand command = new OleDbCommand
(
"Select ID,Data FROM [Data$]", connection); connection.Open(); // Create DbDataReader to Data Worksheet using (DbDataReader dr = command.ExecuteReader()) { // SQL Server Connection String string sqlConnectionString = "Data Source=.;
Initial Catalog=Test;Integrated Security=True
"; // Bulk Copy to SQL Server using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName = "ExcelData"; bulkCopy.WriteToServer(dr); } } }

 

Kalit Sikka replied to Rajiv Sharma on 26-Jul-11 05:06 AM
Easiest way: use SQL Server Import and Export Wizard in Management studio

To use the SQL Server Import and Export Wizard for importing and exporting data

  1. Start the SQL Server Import and Export Wizard.

  2. On the corresponding wizard pages, select a data source and a data destination.

    The available data sources include .NET Framework data providers, OLE DB providers, SQL Server Native Client providers, ADO.NET providers, Microsoft Office Excel, Microsoft Office Access, and the Flat File source. Depending on the source, you set options such as the authentication mode, server name, database name, and file format.

    3.   Set the options for the type of destination that you selected.

  1. (Optional) Select one table and change the mappings between source and destination columns, or change the metadata of destination columns:

    • Map source columns to different destination columns.

    • Change the data type in the destination column.

    • Set the length of columns with character data types.

    • Set the precision and scale of columns with numeric data types.

    • Specify whether the column can contain null values.

  2. (Optional) Select multiple tables, and update the metadata and options to apply to those tables:

    • Select an existing destination schema or provide a new schema to which to assign tables.

    • Specify whether to enable identity inserts in destination tables.

    • Specify whether to drop and re-create destination tables.

    • Specify whether to truncate existing destination tables.

  3. Save and run a package.

    If the wizard is started from SQL Server Management Studio or the command prompt, the package can run immediately. You can optionally save the package to the SQL Server msdb database or to the file system. For more information about the msdb database, see http://msdn.microsoft.com/en-us/library/ms137916.aspx.

    When you save the package you can set the package protection level, and if the protection level uses a password, provide the password. For more information about package protection levels, see http://msdn.microsoft.com/en-us/library/ms141747.aspx.

    If the wizard is started from an Integration Services project in Business Intelligence Development Studio, you cannot run the package from the wizard. Instead, the package is added to the Integration Services project from which you started the wizard. You can then run the package in Business Intelligence Development Studio.

Refer: http://msdn.microsoft.com/en-us/library/ms140052.aspx
Reena Jain replied to Rajiv Sharma on 26-Jul-11 06:05 AM
hi,

Just a little bit of code transfers the data from the Excel Spreadsheet into the SQL Server Database Table:

// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft
  .Jet.OLEDB.4.0;Data Source=Book1.xls;Extended
  Properties=""Excel 8.0;HDR=YES;""";
 
// Create Connection to Excel Workbook
using (OleDbConnection connection =
     new OleDbConnection(excelConnectionString))
{
  OleDbCommand command = new OleDbCommand
    ("Select ID,Data FROM [Data$]", connection);
 
  connection.Open();
   
  // Create DbDataReader to Data Worksheet
  using (DbDataReader dr = command.ExecuteReader())
  {
  // SQL Server Connection String
  string sqlConnectionString = "Data Source=.;
     Initial Catalog=Test;Integrated Security=True";
 
  // Bulk Copy to SQL Server
  using (SqlBulkCopy bulkCopy =
       new SqlBulkCopy(sqlConnectionString))
  {
    bulkCopy.DestinationTableName = "ExcelData";
    bulkCopy.WriteToServer(dr);
  }
  }
}

SqlBulkCopy will import / export your Excel Spreadsheet information into a SQL Server Database Table at very high speeds.

hope this will help you
Reena Jain replied to Rajiv Sharma on 26-Jul-11 06:05 AM

hello,


then just try this on click even of import


The OPENROWSET feature in SQL Server and MSDE provides a fast and easy way to open an OLE DB compatible data source, such as an Excel sheet, directly from your SQL script. Coupled with the "SELECT * INTO" command, the OPENROWSET feature can import data from an Excel sheet into a table in SQL Server or MSDE.

Run the following command from the SQL window in http://www.teratrax.com/tdm. This example uses the OLE DB Provider for Microsoft Excel to access sheet1 in the Excel file c:\book1.xls.


SELECT *
INTO db1.dbo.table1
FROM OPENROWSET('MSDASQL',
    'Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\book1.xls',
    'SELECT * FROM [sheet1$]')


table1 will be created in the db1 database. The content of this table will be imported from the sheet1 worksheet in your c:\book1.xls Excel file.

Radhika roy replied to Rajiv Sharma on 26-Jul-11 11:06 AM
If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow below steps

1. Lets take an example to import the data to SQL Server table, I am going to import student information data from ms excel sheet totStudent SQL table, 

My Excel sheet structure is looks like 
http://2.bp.blogspot.com/_W4LNxazNBjw/SYciBi4KL-I/AAAAAAAAAB0/yli5HdkERg8/s1600-h/ExcellImportData.JPG

2. Now design a tStudent table in SQL server 
Create Table 

StudentName varchar(64), 
RollNo varchar(16), 
Course varchar(32), 


your ms excel sheet and SQL table is ready, now its time to write c# code to import the excel sheet into tStudent table 

3. 
Add these two name space in your class file 

using System.Data.OleDb;

using System.Data.SqlClient;


Use following code 

public void importDataFromExcel(string excelFilePath)

{

//Declare Variables - Edit these based on your particular situation

string sSQLTable = "tDataMigrationTable";

// make sure your sheet name is correct, here sheet name is Sheet1, so you can change your sheet name if have different

string myExcelDataQuery = "Select StudentName,RollNo,Course from [Sheet1$]";

try

{

//Create our connection strings

string sExcelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";Extended Properties=""\"Excel 8.0;HDR=YES;\"";

string sSqlConnectionString = "SERVER=MyDatabaseServerName;USER ID=DBUserId;PASSWORD=DBUserPassword;DATABASE=DatabaseName;CONNECTION RESET=FALSE";

//Execute a query to erase any previous data from our destination table

string sClearSQL = "DELETE FROM " + sSQLTable;

SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);

SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);

SqlConn.Open();

SqlCmd.ExecuteNonQuery();

SqlConn.Close();

//Series of commands to bulk copy data from the excel file into our SQL table

OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);

OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);

OleDbConn.Open();

OleDbDataReader dr = OleDbCmd.ExecuteReader();

SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);

bulkCopy.DestinationTableName = sSQLTable;

while (dr.Read())

{

bulkCopy.WriteToServer(dr);

}

OleDbConn.Close();

}

catch (Exception ex)

{

//handle exception

}

}

In above function you have to pass ms excel file path as a parameter, if you want to import your data by providing client an access to select the excel file and import, then you might have to use http://asp.net/ file control, and upload the excel file on the server in some temp folder, then use the file path of the upload excel file and pass the path in above function. Once data import is completed then you can delete temporary file.

The above method , first delete the existing data from the destination table, then import the excel data into the same table. 


dipa ahuja replied to Rajiv Sharma on 26-Jul-11 12:16 PM
Try this code
private void button2_Click(object sender, EventArgs e)
{
  string ExcelConstr = @"Provider=Microsoft.ACE.OLEDB.12.0";
  ExcelConstr += "Data Source=d:\book1.xls;Extended Properties=Excel 12.0";
  string SqlConstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;";
  SqlConstr += "Integrated Security=True;User Instance=True";
  using (OleDbConnection con = new OleDbConnection(ExcelConstr))
  {
    con.Open();
    OleDbCommand com = new OleDbCommand("Select * from [Sheet1$]", con);
    OleDbDataReader dr = com.ExecuteReader();
    using (SqlConnection sqlcon = new SqlConnection(Program.c))
    {
      sqlcon.Open();
      using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlcon))
      {
        bulkCopy.DestinationTableName = "Table1";
        bulkCopy.ColumnMappings.Add("srno""srno");
        bulkCopy.ColumnMappings.Add("amount""amount");
        bulkCopy.WriteToServer(dr);
      }
    }
    dr.Close();
    dr.Dispose();
  }
  MessageBox.Show("successfully imported!");
  //display the imported data in the datagrid
  SqlDataAdapter da = new SqlDataAdapter("select * from Table1"Program.c);
  DataTable dt = new DataTable();
  da.Fill(dt);
  dataGridViewX1.DataSource = dt;
}