Tutorial – Read and export excel file in ASP.Net using C#

Author posted by Jitendra on Posted on under category Categories ASP.NET, c# and tagged as Tags , with 1 Comment on Tutorial – Read and export excel file in ASP.Net using C#

Tutorial – Read and export excel file in ASP.Net using C#

Hi Readers,
In this article, i am going to show you that how to read excel file in C# and exporting it into ASP.Net. You might need this type of code when you want to read the file from server and export to the client.
Following will be the application look like :

Read And Export Excel in ASP.Net
Read And Export Excel in ASP.Net


Asp.Net Code:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.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" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnExport" Text="Click To Export" runat="server" OnClick="btnExport_Click" />
        <br />
        <strong><span style="text-decoration: underline">
        Note :</span></strong> Excel path is picked up from web.Config
    </div>
    </form>
</body>
</html>

C# Code :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        try
        {
            string filePath = string.Empty;
            if (ConfigurationManager.AppSettings["FilePath"] != null)
            {
                filePath = ConfigurationManager.AppSettings["FilePath"].ToString();
            }

            byte[] document = this.StreamFile(filePath);
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=TestExcel" + Convert.ToString(DateTime.Now.ToFileTimeUtc()) + ".xls");
            Response.Charset = "";
            Response.Cache.SetNoServerCaching();
            Response.ContentType = "application/ms-excel";
            Response.BinaryWrite(document);
            Response.End();
        }
        catch (Exception ex)
        {
            Page.RegisterStartupScript("error", "<script>alert('Some error occured. Please contact admin. ');</script>");
        }
    }

    /// <summary>
    /// Streams the file.
    /// </summary>
    /// <param name="filename">The filename.</param>
    /// <returns></returns>
    /// <remarks></remarks>
    private byte[] StreamFile(string filename)
    {
        byte[] ImageData = new byte[0];
        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        try
        {
            // Create a byte array of file stream length
            ImageData = new byte[fs.Length];
            //Read block of bytes from stream into the byte array
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
            //Close the File Stream

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
        return ImageData;
        //return the byte data
    }
}

Download source code of Read and Export to excel

Related posts

  • Susanne Maltez

    Hi there. Very cool blog!! Guy .. Excellent .. Wonderful .. I will bookmark your site and take the feeds additionally…I’m satisfied to find numerous helpful info here within the post. Thanks for sharing…