Search This Blog

Thursday 26 May 2016

How to Download DataTable to Text File in Asp.Net?

 Step 1:- Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Download File</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" />
        </div>
    </form>
</body>
</html>

Step 2:- Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
        }

        protected DataTable BindData()
        {
            DataTable dt = new DataTable();

            DataRow dr = null;

            dt.Columns.Add(new DataColumn("RowNumber"typeof(string)));

            dt.Columns.Add(new DataColumn("Column1"typeof(string)));

            dt.Columns.Add(new DataColumn("Column2"typeof(string)));

            dt.Columns.Add(new DataColumn("Column3"typeof(string)));

            int totalRow = 15;

            for (int i = 0; i < totalRow; i++)
            {
                dr = dt.NewRow();

                dr["RowNumber"] = i + 1;

                dr["Column1"] = "Row" + i;

                dr["Column2"] = "Row" + i;

                dr["Column3"] = "Row" + i;

                dt.Rows.Add(dr);
            }

            return dt;
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            string strDD = DateTime.Now.ToString("dd");
            string strMM = DateTime.Now.ToString("MM");
            string strYY = DateTime.Now.ToString("yyyy");

            string strDate = strDD + "" + strMM + "" + strYY;

            string fileName = "Demo_" + strDate + ".txt";

            string filePath = Server.MapPath(@"~\Download\" + fileName);

            // If file already exists in path then delete
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            // If Download folder not exists in path then create
            if(!Directory.Exists(Server.MapPath(@"~\Download\")))
            {
                Directory.CreateDirectory(Server.MapPath(@"~\Download\"));
            }

            StreamWriter sw = new StreamWriter(filePath, falseEncoding.Default);

            foreach (DataColumn dataColumn in BindData().Columns)
            {
                string column = string.Empty;

                column += dataColumn.ColumnName.ToString().PadRight(15);
       
                sw.Write(column);
            }

            sw.WriteLine(Environment.NewLine);

            foreach (DataRow dataRow in BindData().Rows)
            {
                string row = string.Empty;
                foreach (object item in dataRow.ItemArray)
                {
                    row += item.ToString().PadRight(15);
                }
                sw.WriteLine(row);
            }
            sw.Flush();
            sw.Close();

            FileStream fs = null;
            fs = File.Open(filePath,FileMode.Open);
            byte[] byteFile = new byte[fs.Length];
            fs.Read(byteFile, 0, (int)fs.Length);
            fs.Close();

            Response.AddHeader("Content-disposition""attachment; filename=" + fileName);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(byteFile);
            Response.End();
        }
    }
}

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete