Read and insert bulk of data from excel to database in one shot.


Read and insert bulk of data from excel to database in one shot with the help of dataset.

Hi friends,
Thought I will share a small utility which will be useful for reading from excel and insert into database. A simple tool which reads from excel using the microsoft.interop.excel library. And then whole data is inserted into a DataSet. From which the records and inserted into the database with a single DataAdapter.Update() call. Simple, easy and fast way of inserting records to sql database.

Below is a piece of code to read from excel.


using Microsoft.Office.Interop.Excel;

Application ExcelObj = new Application();

Workbook theWorkbook = ExcelObj.Workbooks.Open(@"filenamepath", Type.Missing, Type.Missing, Type.Missing, Type.Missing,

Type.Missing, Type.Missing, Type.Missing, Type.Missing,

Type.Missing, Type.Missing, Type.Missing, Type.Missing,

Type.Missing, Type.Missing);

Sheets sheets = theWorkbook.Worksheets;

Worksheet worksheet = (Worksheet)sheets.get_Item(1);


And here is a code block to insert the records to database.

DataSet empDataSet = new DataSet();
string sqlConnectionString = @"Data Source=machine\SQLEXPRESS;Initial Catalog=Sample;Trusted_Connection=True;";
SqlConnection newConnection = new SqlConnection(sqlConnectionString);
SqlDataAdapter newAdapter = new SqlDataAdapter("Select * from Employee", newConnection);
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(newAdapter);
newAdapter.Fill(empDataSet, "Employee");
BuildDataSet(strArray, ref empDataSet);
newAdapter.Update(empDataSet, "Employee");


Please download the attached full project for the rest of the code. And let me know your feedback.


Comments

Author: DAMU23 Oct 2010 Member Level: Gold   Points : 0

Hello Anil,

Where is the attachment? Where can i download?

Author: anil08 Nov 2010 Member Level: Gold   Points : 1

Hi Damodhar,
Please check the place below the title of this article. On the right hand side you can see a link called "attachments", click on it and download the attached files. Get back if you have any other issues on downloading the same.

Thanks,
Anil.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: