Wednesday, 13 November 2013

EXPORT DATA IN EXCEL SHEET USING ASP.NET C#

  public static void ExportToExcel(DataTable dt, string fileName)
    {
        if (dt != null)
        {
            HttpContext cont = HttpContext.Current;
            cont.Response.Clear();

            string header = "attachment; filename=" + fileName + ".xls";
            cont.Response.AppendHeader("content-disposition", header);
            cont.Response.ContentType = "application/vnd.ms-excel";

            StringBuilder sb = new StringBuilder();

            // Render out an HTML table to pass into Excel
            sb.Append("<table cellpadding=2 cellspacing=2>");

            // Get all column names
            sb.Append("<tr>");

            foreach (DataColumn dc in dt.Columns)
            {
                sb.Append("<td>");

                sb.Append("<b>" + dc.ColumnName.Replace("_", " ") + "</b>");

                sb.Append("</td>");
            }

            sb.Append("</tr>");

            // Handle table rows and cells
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("<tr>");

                foreach (DataColumn dc in dt.Columns)
                {
                    sb.Append("<td>");

                    sb.Append(dt.Rows[i][dc].ToString());

                    sb.Append("</td>");
                }

                sb.Append("</tr>");
            }

            // Close the table tag
            sb.Append("</table>");

            dt.Dispose();

            // Pass the table HTML string into the response output stream to be passed to Excel
            cont.Response.Write(sb.ToString());
            cont.Response.End();
            cont.Response.Clear();
        }
        else
        {
            throw new Exception("The data table cannot be null.");
        }
    }



U CAN CALL THIS METHOD LIKE BELOW IN PAGE LOAD

 ExportToExcel( dt,filename  );

Sample Project for downloading Files in ZIP Format

for .cs file we use this below code
----------------------------------

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Calling the function of Grid View Bind
            BindGridview();
        }

    }
    protected void BindGridview()
    {
        // Creation of String arrary to store path
        string[] getfilesPath = Directory.GetFiles(Server.MapPath("~/FilesUploaded/"));
        // Adding files to list
        List<ListItem> files = new List<ListItem>();
        foreach (string path in getfilesPath)
        {
            //Adding files to the list item
            files.Add(new ListItem(Path.GetFileName(path)));
        }
        xfiles.DataSource = files;
        xfiles.DataBind();
    }


    protected void btnUpload_Click(object sender, EventArgs e)
    {
        // Uploading the Files to the folder
        if (xfuupload.HasFile)
        {
            string filename = Path.GetFileName(xfuupload.PostedFile.FileName);
            xfuupload.SaveAs(Server.MapPath("FilesUploaded/") + filename);
            xlit.Text = "File Uploaded Successfully";
            BindGridview();
        }
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        // Creating an Object of ZipFile Class in Iconic.Zip dll
        ZipFile creatingzip = new ZipFile();
        //Finding the Checkbox Control and checking which of the files are selected using the check box
        foreach (GridViewRow gvrow in xfiles.Rows)
        {
            CheckBox chk = (CheckBox)gvrow.FindControl("chkselectfordownload");
            if (chk.Checked)
            {
                string fileName = gvrow.Cells[1].Text;
                string filePath = Server.MapPath("~/FilesUploaded/" + fileName);
                // Adding the file to Zip Archieve
                creatingzip.AddFile(filePath, "files");
            }
        }
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=Downloads.zip");
        // Setting the content type to ZIP
        Response.ContentType = "application/zip";
        creatingzip.Save(Response.OutputStream);
        Response.End();
    }


for designing page
------------------
<form id="form1" runat="server">
     Sample Project for downloading Files in ZIP Format<p>
        <asp:FileUpload ID="xfuupload" runat="server" /> <br /><br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload"
            onclick="btnUpload_Click" />
    </p>
    <p>
        <asp:Literal ID="xlit" runat="server"></asp:Literal>
    </p>

    <div>
     <asp:GridView ID="xfiles" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Select Files">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkselectfordownload" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Text" HeaderText="Files" />
            </Columns>
        </asp:GridView>
        <br />
        <br />
        <asp:Button ID="btnDownload" runat="server" Text="Download Selected Files"
            onclick="btnDownload_Click" />

    </div>
    </form>



output like this





SEND EMAILS FROM YOUR APPLICATIONS

 SEND EMAIL FROM YOUR APPLICATION

protected void BtnSave_Click(object sender, EventArgs e)
    {
        string attachment = string.Empty;
        string emailList = string.Empty;
           
        foreach (GridViewRow curRow in GdvEmail.Rows)
        {
            CheckBox chkSelect = (CheckBox)curRow.FindControl("chkRow");
            if (chkSelect.Checked)
            {
                if (emailList != "")
                {
                    emailList = emailList + ";" + curRow.Cells[1].Text;
                }
                else
                {
                    emailList = curRow.Cells[1].Text;
                }
            }
        }
        if (emailList != "")
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new NetworkCredential("rajendar1210@gmail.com", "01234@56789");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            MailMessage message = new MailMessage();
            message.From = new MailAddress("rajendar1210@gmail.com");
            if (emailList.Contains(";"))
            {
                string[] _EmailsTO = emailList.Split(";".ToCharArray());
                for (int i = 0; i < _EmailsTO.Length; i++)
                {
                    message.To.Add(new MailAddress(_EmailsTO[i]));
                }
            }
            else
            {
                if (!emailList.Equals(string.Empty))
                {
                    message.To.Add(new MailAddress(emailList));
                }
            }
            if (FileUploadEmail.PostedFile != null)
            {

                HttpPostedFile attFile = FileUploadEmail.PostedFile;

                int attachFileLength = attFile.ContentLength;

                if (attachFileLength > 0)
                {

                    string FileNameToAttache = Path.GetFileName(FileUploadEmail.PostedFile.FileName);
                    FileNameToAttache = "attachments/" + FileNameToAttache;
                    FileUploadEmail.PostedFile.SaveAs(Server.MapPath(FileNameToAttache));

                    message.Attachments.Add(new Attachment(Server.MapPath(FileNameToAttache)));
                    attachment = FileNameToAttache;

                }

            }
            message.Subject = txtSubject.Text.Trim();
            message.Body = TxtMessage.Text.Trim();
            smtp.Timeout = 9999999;
            smtp.Send(message);
            if (File.Exists(attachment))
            {

                if (IsFolderReadOnly(attachment))
                {
                    System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo(attachment);
                    oDir.Attributes = oDir.Attributes & ~System.IO.FileAttributes.ReadOnly;
                }

                File.Delete(attachment);//Error is thrown from here

            }
            attachment = null;

            Page.RegisterStartupScript("Sathyam Computer Education", "<script>alert('Mail sent thank you...');if(alert){ window.location='EmailNotification.aspx';}</script>");
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "ShowAlert", "alert(' Select the email in the grid ')", true);
        }
    }