Apr 14, 2009

How to Insert into Excel file from another Excel file

In this I have excel database I want to creat a asp.net page that will allow my user to browse a excel file from aspx page and insert into the file.

example i have excel file which has 2 column, 1 bedroom 2bathroom.Now in my asp.net page I have fileupload and one Click button.User will browse a excel file and click the button.These information will be inserted into Excel file.



// .aspx

<div>

<asp:FileUpload ID="fileUpload" runat="server" />

<asp:Button ID="btnSumbit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

div>

// Code Behind

protected void btnSubmit_Click(object sender, EventArgs e)

{

string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= ;Extended Properties=Excel 8.0;";

if (fileUpload.HasFile)

{

Guid name = Guid.NewGuid();

fileUpload.SaveAs(Server.MapPath("NewFolder1\\" + name + "_" + fileUpload.FileName));

string newstr = connString.Insert(46, Server.MapPath("NewFolder1/" + name + "_" + fileUpload.FileName));

OleDbConnection oledbConn = new OleDbConnection(newstr);

DataSet ds = new DataSet();

oledbConn.Open();

// Create OleDbCommand object and select data from worksheet Sheet1

OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);

// Create new OleDbDataAdapter

OleDbDataAdapter oleda = new OleDbDataAdapter();

oleda.SelectCommand = cmd;

// Create a DataSet which will hold the data extracted from the worksheet.

// Fill the DataSet from the data extracted from the worksheet.

oleda.Fill(ds);

oledbConn.Close();

string connString1 = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= ;Extended Properties=Excel 8.0;";

string newStr1 = connString1.Insert(46, Server.MapPath("")+"\\Sample.xlsx");

OleDbConnection oledbConn1 = new OleDbConnection(newStr1);

oledbConn1.Open();

string query = "Insert into [Sheet1$] (Bathroom,Bedroom) values(" + "'" + ds.Tables[0].Rows[0][0] + "'," + "'" + ds.Tables[0].Rows[0][1] + "')";

OleDbCommand cmd1 = new OleDbCommand();

cmd1.Connection=oledbConn1;

cmd1.CommandText=query;

cmd1.ExecuteNonQuery();

oledbConn1.Close();

}

}




2 comments:

Nitin Sharma said...

Upender ...this is Good one...But isn't it too lengthy...??Right??

Alex said...

At work with Excel files I often use next software-recover modified Excel worksheets,it to myself advised my brother,he said that tool is free and is quite reliable,moreover it can repair corrupted Microsoft Excel worksheets,restore data after problems with corrupted worksheet problem as a result of virus attack, disk and network failures or any other problem,an scan a damaged Microsoft Excel worksheet and repair it,work with *.xls, *.xlam, *.xltx, *.xlt and *.xlsm formats,recover modified Excel worksheets and shows recovered data in the same way, like it will be displayed in Microsoft Excel worksheet.