Introduction
Recently I worked on a site in which we were required to import excel in website and calculate internal fields then display in grid view and save data in database then export to excel File.
That was really nice and I decided to put the code here.
<%@ Page Language="C#" AutoEventWireup="true"CodeFile="Export_excel_.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Import Excel Data into GridView & Again Export to Excel Sheet</title>
<script language="javascript" type="text/javascript">
function exportToExcel() {
var oExcel = new ActiveXObject("Excel.Application");
var oBook = oExcel.Workbooks.Add;
var oSheet = oBook.Worksheets(1);
var dt = document.getElementById('tbl')
for (var y = 0; y < dt.rows.length; y++)
// detailsTable is the table where the content to be exported is
for (var x = 0; x < dt.rows(y).cells.length; x++)
oSheet.Cells(y + 1, x + 1) = dt.rows(y).cells(x).innerText;
oExcel.UserControl = true;
<form id="form1" runat="server">
<table cellpadding="10" cellspacing="10" style="font-family: Arial; font-size: 12px;
border: solid 1px #ccc;" border="1" align="center">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"/>
<td align="center" colspan="2">
<asp:GridView ID="GridView1" runat="server" AllowPaging="false"OnPageIndexChanging="PageIndexChanging">
<HeaderStyle CssClass="hdr" />
<FooterStyle CssClass="ftr" />
<td align="center" colspan="2">
<asp:GridView ID="GridView2" runat="server" AllowPaging="false">
<HeaderStyle CssClass="hdr1" />
<RowStyle CssClass="Row" />
<AlternatingRowStyle CssClass="Alt" />
<td align="center" colspan="2">
<asp:Button ID="Save_ExporttoExcel" runat="server" Text="Save to DB & Export to Excel"
OnClientClick="exportToExcel()" OnClick="Save_ExporttoExcel_Click" />
<td colspan="2" align="center">
<asp:Label ID="lblError" runat="server" Text="Label"></asp:Label>
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
lblError.Visible = false;
protected void btnUpload_Click(object sender, EventArgs e)
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string FilePath = Server.MapPath(FolderPath + FileName);
FileUpload1.SaveAs(FilePath);
Import_To_Grid(FilePath, Extension);
private void Import_To_Grid(string FilePath, string Extension)
case ".xls": //Excel 97-03
conStr =ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
conStr =ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
conStr = String.Format(conStr, FilePath, 1);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
//Read Data from First Sheet
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
GridView1.DataSource = dt;
DataTable dttable_data = new DataTable();
dttable_data = dt; //Return Table consisting data
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add(" S. No.");
dtTemp.Columns.Add(" Student Name ");
dtTemp.Columns.Add(" Roll No ");
dtTemp.Columns.Add(" Total Marks ");
dtTemp.Columns.Add(" Percentage");
for (int i = 0; i < dttable_data.Rows.Count; i++)
drAddItem = dtTemp.NewRow();
drAddItem[0] = dttable_data.Rows[i]["S# No#"].ToString();
drAddItem[1] = dttable_data.Rows[i]["Student Name"].ToString();//Student Name
drAddItem[2] = dttable_data.Rows[i]["Roll No#"].ToString();//Roll No
sum = (int.Parse(dttable_data.Rows[i]["Hindi"].ToString()) +int.Parse(dttable_data.Rows[i]["English"].ToString()) + int.Parse(dttable_data.Rows[i]["Maths"].ToString()) + int.Parse(dttable_data.Rows[i]["Physics"].ToString()));
drAddItem[3] = sum.ToString();
int prcnt = (sum*100/800);
drAddItem[4] = prcnt.ToString();
dtTemp.Rows.Add(drAddItem);
//Bind Data with Grid View
GridView2.DataSource = dtTemp;
protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string FileName = GridView1.Caption;
string Extension = Path.GetExtension(FileName);
string FilePath = Server.MapPath(FolderPath + FileName);
Import_To_Grid(FilePath, Extension);
GridView1.PageIndex = e.NewPageIndex;
private void creatExcel()
if (Int32.Parse(GridView2.Rows.Count.ToString()) < 65536)
GridView2.AllowPaging = true;
//grvProdReport.DataBind()
StringWriter tw = new StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
HtmlForm frm = new HtmlForm();
string strTmpTime = (System.DateTime.Today).ToString();
if (strTmpTime.IndexOf("/") != -1)
strTmpTime = strTmpTime.Replace("/", "-").ToString().Trim();
if (strTmpTime.IndexOf(":") != -1)
strTmpTime = strTmpTime.Replace(":", "-").ToString().Trim();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=sheet.xls");
Response.Charset = "UTF-8";
frm.Controls.Add(GridView2);
hw.WriteLine("<b> <u> <font-size:'5'> Student Report </font> </u> </b>");
Response.Write(tw.ToString());
lblError.Text = "Export to Excel not possible";
// insert value in database
string s = ConfigurationManager.ConnectionStrings["test_"].ConnectionString;
SqlConnection con = new SqlConnection(s);
for (i = 0; i <= GridView1.Rows.Count - 1; i++)
string query = "insert into tbl_studentsummary values ('" + GridView2.Rows[i].Cells[0].Text + "','" + GridView2.Rows[i].Cells[1].Text.ToString() + "','" + GridView2.Rows[i].Cells[2].Text + "','"+ GridView2.Rows[i].Cells[3].Text + "','" + GridView2.Rows[i].Cells[4].Text + "')";
SqlCommand cmd = new SqlCommand(query,con);
lblError.Text = "Sucessfull";
protected void Save_ExporttoExcel_Click(object sender, EventArgs e)
inst_data(); // insert data in database.
creatExcel(); // Creat Excel File
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name="test_" connectionString="Data Source=XCEEDSTUDIO;Initial Catalog=test_;Persist Security Info=True;User ID=sa;Password=12345"/>